what is the preferred way to mutate a React state?
JavascriptReactjsJavascript Problem Overview
Let's say I have a list of plain objects in my this.state.list
that I can then use to render a list of children. What then is the right way to insert object into this.state.list
?
Below is the only way I think it will work because you can not mutate the this.state
directly as mentioned in the doc.
this._list.push(newObject):
this.setState({list: this._list});
This seems ugly to me. Is there a better way?
Javascript Solutions
Solution 1 - Javascript
concat
returns a new array, so you can do
this.setState({list: this.state.list.concat([newObject])});
another alternative is React's immutability helper
var newState = React.addons.update(this.state, {
list : {
$push : [newObject]
}
});
this.setState(newState);
Solution 2 - Javascript
[setState()][1] can be called with a function as a parameter:
this.setState((state) => ({ list: state.list.concat(newObj) }))
or in ES5:
this.setState(function(state) {
return {
list: state.list.concat(newObj)
}
})
[1]: http://devdocs.io/react/docs/component-api#setstate "setState"
Solution 3 - Javascript
Update 2016
With ES6 you can use:
this.setState({ list: [...this.state.list, ...newObject] });
Solution 4 - Javascript
From the react docs (https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous):
> Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
So you should do this instead:
this.setState((prevState) => ({
contacts: prevState.contacts.concat([contact])
}));