-1

The following is my state.

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

};

I need add new words in user by id 1 with setState.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • Possible duplicate of [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs) – Emile Bergeron Aug 06 '19 at 15:29

3 Answers3

0

You can map the users object and update the relevant user, like:

this.setState(state => ({
  ...state,
  users: state.users.map(user => user.id === 1 ? {
    ...user,
    words: [...user.words, 'new', 'words']
  } : user)
}))
CD..
  • 72,281
  • 25
  • 154
  • 163
0

You can add a word to a user like this (assuming words passed in is an array of new words)

addWords = (i, words) => {
    this.setState(prevState => {
        return {
            users: [...prevState], 
            users[i]: {
                ...prevState.users[i], 
                words: [...prevState.users[i].words, ...words]
            }
        }
    })
}

Then call it like this

<button onClick={() => this.addWords(userIndex, ["new","word"])}>
    Add words
</button>

This way you can add words to any user

Shmili Breuer
  • 3,927
  • 2
  • 17
  • 26
-1

You can use a library like immutability-helper or with es6:

// ES6
const users = this.state.users.map(user => 
     user.id === 1 ? {...user, words: ['new', 'words', 'can', 'be', 'push', 'here']} : user)
this.setState({users})

Using immutable-js will be like:

import update from "immutability-helper";

this.setState({
    users: update(this.state.users, {
        [1]: {words: {$push: ['new', 'items']}}
    })
})