Rafael Winterhalter
Rafael Winterhalter

Reputation: 43997

Chaining state updates

I wrote code that distributes logic among several components. Currently, those trigger individual state updates via callbacks, correspondig to a control flow similar to:

this.state({foo: React.addons.update(this.state.foo, {$push: 'bar'})});
...
this.state({foo: React.addons.update(this.state.foo, {$push: 'qux'})});

Unfortunately, the second push overwrites the first one as React does not update the state variable immediately but only after the callback was executed. Is there a way of comitting the changes of the first state update in order to retain the first one?

Upvotes: 0

Views: 1312

Answers (1)

noveyak
noveyak

Reputation: 3300

I think you need to make sure you are referencing the previous state when you update your new state. I don't think the React.addons.update code is helping here - are you using it to not mutate the array thats in state?

You can access the previous state if you pass a function to setState instead of just an object. Create a jsfiddle below which has 2 divs with your current code and one that I think does what you want.

https://facebook.github.io/react/docs/component-api.html

handleClick2:function(){
    this.setState(function(previousState, currentProps) {
        return {text2: previousState.text2.concat(['foo'])};
    });
    this.setState(function(previousState, currentProps) {
        return {text2: previousState.text2.concat(['bar'])};
    });
},

https://jsfiddle.net/sa4vvtjL/

Upvotes: 1

Related Questions