My component's state is an array of objects:
this.state = {
userFavorites: [{id: 1, title: 'A'}, {id: 2, title: 'B'}]
}
I need to, everytime I click in a button, update my state with another object like the ones I have in my state above; for example: {id: 3, title: 'C'}.
If I simply concat them and set the state, the last object keeps being changed by the one that's being added.
Do I need the spread operator here?
My component's state is an array of objects:
this.state = {
userFavorites: [{id: 1, title: 'A'}, {id: 2, title: 'B'}]
}
I need to, everytime I click in a button, update my state with another object like the ones I have in my state above; for example: {id: 3, title: 'C'}.
If I simply concat them and set the state, the last object keeps being changed by the one that's being added.
Do I need the spread operator here?
Share Improve this question asked Oct 23, 2018 at 17:40 Rafael GuedesRafael Guedes 3392 gold badges5 silver badges11 bronze badges 7 | Show 2 more comments4 Answers
Reset to default 6You should do it this way. Below is the most recommended way to push values or objects to an array in react
this.setState( prevState => ({
userFavorites: [...prevState.userFavourites, {id: 3, title: 'C'}]
}));
To push to the beginning of the array do it this way
this.setState( prevState => ({
userFavorites: [{id: 3, title: 'C'}, ...prevState.userFavourites]
}));
for functional component
const [userFavorites, setUserFavorites] = useState([]);
setUserFavorites((prev) => [...prev, {id: 3, title: 'C'}])
There are multiple ways to do this. The simplest way for what you are needing to do is to use the spread operator. Note that item is the object being added to userFavorites.
this.setState({
userFavorites: [ ...this.state.userFavorites, item ],
});
Note: If at some point down the line you are needing to update a specific item in the array, you could use the update function from the immutability-helpers library. https://reactjs.org/docs/update.html
const userFavorites = [...this.state.userFavorites, {id: 3, title: 'C'}]
this.setState({ userFavorites })
push
? – brk Commented Oct 23, 2018 at 17:42