Using the Spread syntax in React Js to set state array of object

Mirthful Nahid
NAHID HASAN
Published in
2 min readFeb 23, 2018

--

In React , we all use setState to update the state . i was having some issue about updating the state of a array of Object to an empty state array.

Like This, the initial state.

this.state = { cars : [] }

i had to update the state to an array of object like this.

var carArray = [{ name : ‘Ford’ , price : 15000 }, { name : ‘toyota’ , price : 12000 } , { name : ‘Rover’ , price : 14000 }]

i was using this to update my state.

this.setState({
cars: [ this.state.cars, carArray ]
})

But there was i little bit of problem in that . i was just pushing the object into the empty array at second index .

So, there is little problem , i cannot just map over them straight. i have tell there index too.

this.state.car[1].map((data, i) => (<ul key={i}><li> {data.name} </li><li> {data.price} </li></ul>

then i found Spread syntax . i saw some tutorial on it . then i understood this is actually what i needed for easy copying and mapping . So , instead i used this ..

this.setState({
cars: [ ...this.state.cars, ...carArray ]
})

and ta da … just what i needed …

console logging this time

Now i can easily map over them !!

actually what happened is that in the previous case , i have that extra 0 index . Now i don’t have. then i stated playing with other options and watch what’s happening .

this.setState({
cars: [ ...this.state.cars, carArray ]
})

and

this.setState({
cars: [ this.state.cars, ...carArray ]
})

for this two , i got this ,

for using … only for first item

and this,

for using … only for second item

can you see from the pictures, whats happening ?

i hope you do.

for Hooks : Update

setCar(…car, …carArray)

Thanks , Have Fun .

See you later. :)

--

--