ReactJS - setState key of an object in an array

So, I worked on this for some time and thought it was best to reorganize my code so that the state was configured as an array of objects. What I'm trying to do is increase the number with the click of a button.

I have a callback function in a component that runs a function to update the state ... however, I am having difficulty targeting a key value inside an object.

My initial state is as follows:

getInitialState: function() { return { items: [ { links: 'zest', trackId: 1023, songTitle: 'z know the others', artist: 'zuvet', upVotes: 0 }, { links: 'alpha', trackId: 987, songTitle: 'ass', artist: 'arme', upVotes: 3 }, ] } 

I am trying to target upVotes , but cannot figure out how to do this. My function passes the key so that I can target the index in the array, but when I try to do something like: this.setState({items[key]: {upVotes: this.state.items[key].upVotes + 1}}) , it gives an error due to an unexpected token [ .

I tried something similar to this thread here , but I keep getting errors.

What function can I write that will only setState for the key in the object I want to configure?

+6
source share
2 answers

Get the current state, change it and setState() it:

 var stateCopy = Object.assign({}, this.state); stateCopy.items[key].upVotes += 1; this.setState(stateCopy); 

Note. . This will result in a state change. Here's how to do it without mutation:

 var stateCopy = Object.assign({}, this.state); stateCopy.items = stateCopy.items.slice(); stateCopy.items[key] = Object.assign({}, stateCopy.items[key]); stateCopy.items[key].upVotes += 1; this.setState(stateCopy); 
+15
source

You can directly change the value in your array and set the state to the changed object, given that you are not using immutable.js, i.e. ...

 this.state.array[i].prop = 'newValue'; this.setState({ array: this.state.array }); 

The problem with direct editing is that React does not know that the state has changed and the update life cycle does not work. But setting the state again forces an update.

- EDIT -

If the state is unchanged ...

 const array = this.state.array.slice(); array[i].prop = 'newValue'; this.setState({ array }); 
+2
source

All Articles