D
D
Durin Qurkingo2019-08-06 18:31:13
React
Durin Qurkingo, 2019-08-06 18:31:13

How can I add items to an object?

Below is my condition.

this.state = {
  text: "",
  users: [
    {id:1, name:"nawaf", words:["sami","nawaf"] },
    {id:2, name:"khaled", words:["sad","ramy"] },
  ]

};

I need to add new words to user with id 1 with setState.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-08-06
@Sagund

updateUser = (id, words) => {
  this.setState(({ users }) => ({
    users: users.map(n => n.id === id
      ? { ...n, words: [ ...n.words, ...words ] }
      : n
    ),
  }));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question