Reputation: 424
I have a constructor like
constructor() {
this.state = {
item_details : {}
}
}
someFunc(next_item_key,next_item_value) {
//append this next_item_key , next_item_value pair to item_detials
}
I need to add this next_item in someFunc to my state variable item_details..
Example: My item_details will look something like this
item_details : {'abc' : 'xyz' , 'a12' : '123' }
My next_item will be like
next_item_key = 'qwerty'
next_item_value = 'pqrs'
My resultant item_details should look like
item_details : {'abc' : 'xyz' , 'a12' : '123' , 'qwerty' : 'pqrs' }
what should i write in someFunc to get this result
Upvotes: 2
Views: 423
Reputation: 104369
Use [] notation and spread operator to achieve that.
Write it like this:
someFunc(next_item_key, next_item_value) {
this.setState(prevState => ({item_details: {
...prevState.item_details,
[next_item_key]: next_item_value}
}))
}
Update:
Calling setState in a loop is not a good idea, better approach will be first do all calculations then update the state value in on shot.
Like this:
let data = {};
response.result.variants.forEach((element) => {
data[element.title]: false;
});
this.setState(prevState => ({in_wishlist: { ...prevState.in_wishlist, ...data }}))
Upvotes: 0
Reputation: 1478
Object.assign should fit your need:
const newState = Object.assign(this.state.item_details, {[next_item_key]: next_item_value})
Or using spread operator:
const newState = {...this.state.itemDetails, [next_item_key]: next_item_value}
Upvotes: 0
Reputation: 3105
You can use the spread operator to keep your previous state:
this.setState(prevState => ({ item_details:
{
...prevState.item_details,
[next_item_key]: next_item_value
}
}));
Upvotes: 2