Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  107] [ 2]  / answers: 1 / hits: 57213  / 8 Years ago, wed, february 3, 2016, 12:00:00

So i've been working on this for awhile and felt it would be best to refactor my code so that the state is set up as an array of objects. What i'm trying to do is increment a number on a button click.



I have a callback function in a component that triggers a function to update the state...however i'm having difficulty targeting the key value within the object.



My initial state looks like this:



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 the upVotes key, but can't figure out how. My function passes a 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 throws an error due to the unexpected [ token.



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



What kind of function can I write that will setState of just the key in the object that I want to target?


More From » reactjs

 Answers
31

Get current state, modify it and setState() it:



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


Note: This will mutate the state. 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);

[#63463] Monday, February 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;