setState is not merging the values

I use the following code in react in order to update state. state should finally looks like this:

this.state.output = {
 'abc':{
     value: 10
 },
 'cde':{
     value: 20
  }
  // new values are added and old kept (if not overwritten)
}

My handler:

 handleChange = (data) => {
    this.setState(prevState => {
      return {
        output: {
          [data.id]: { ...data },
        },
      }
    })
  }

When the data is passed in to handleChage with a new data.id, output does not add the new key, instead completely replace all its content

this.state.output = {
  'new':{
     value: 2
   },
}

I need instead keep the previous key also. What is wrong in my code?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Because you forgot to add the other property and their values, update the object like this:

handleChange = (data) => {
    this.setState(prevState => {
        return {
            output: {
                ...prevState.output,      // notice this
                [data.id]: { ...data },
            },
        }
    })
}

Or simply:

handleChange = (data) => {
    this.setState(prevState => ({
        output: {
            ...prevState.output,
            [data.id]: { ...data },
        },
    })
)}

Solution 2

object spread syntax is recent spec. Here is the documentation for it: using-object-spread-operator

Below code uses Object.assign method instead :

handleChange = (data) => {
    this.setState(prevState => ({
        output: Object.assign({}, prevState, {
        [data.id]: data
      })
    })
)}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply