5

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?

7
  • Why cant you simply use push? Commented Oct 23, 2018 at 17:42
  • Since you're pushing object, you can use spread operator while concatenating. Please don't use push. Commented Oct 23, 2018 at 17:44
  • @vijaykrishna why push cannot be used? Commented Oct 23, 2018 at 17:47
  • newList = [...this.state.user favourites, { id:3, title: 'C' }] Commented Oct 23, 2018 at 17:51
  • @brk this post might help you Commented Oct 23, 2018 at 17:54

4 Answers 4

6

You 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]
  }));
Sign up to request clarification or add additional context in comments.

1 Comment

reverse the order--the OP wants the new object added to the beginning of the array, not the end
4

for functional component

const [userFavorites, setUserFavorites] = useState([]);

setUserFavorites((prev) => [...prev, {id: 3, title: 'C'}])

Comments

2

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

1 Comment

Thank you. This response was immensely helpful. I have been pulling my hair out with the .map() is not a function error. I was obviously pushing incorrectly to the array of objects in state, and which was having a domino effect on the rest of my app. The spread operator was the key. Thank you!
1
const userFavorites = [...this.state.userFavorites, {id: 3, title: 'C'}]
this.setState({ userFavorites })

1 Comment

It keeps being changed by the one that's being added. Not sure if there's some kind of issue with my implementation but this is getting weird.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.