Q:

Proper handling of multiple sequential state updates

This example is a bit contrived, but bear with me. Say I have two functions as members in a React component:
var OrderApp = React.createClass({
    getInitialState: function() {
        return {
            selectedOrders: {},
            selectedLineItems: {}
        };
    },

    setOrderSelected: function(order, newSelectedState) {
        var mutation = {};
        mutation[order.id] = {$set: newSelectedState};
        var newSelectedOrders = React.addons(this.state.selectedOrders, mutation);
        _.each(order.lineItems, function(lineItem) {
            setLineItemSelected(lineItem, newSelectedState);
        });
        this.setState({selectedOrders: newSelectedOrders});
    },

    setLineItemSelected: function(lineItem, newSelectedState) {
        var mutation = {};
        mutation[lineItem.id] = {$set: newSelectedState};
        var newSelectedLineItems = React.addons(this.state.selectedLineItems, mutation);
        this.setState({seelctedLineItems: newSelectedLineItems});
    }
});

At the completion of calling OrderApp.setOrderSelected(order, true), only the last lineItem selected state appears to have changed in my component's state. I'm guessing this is because React is batching the calls to setState, and so when I'm calling:
var newSelectedLineItems = React.addons(this.state.selectedLineItems, mutation);

in the second function, I'm picking up the original state each time, and so only the last mutation takes effect.
Should I be collecting all of the state mutations in the parent function and only calling setState once? This feels a bit clunky to me, and I'm wondering if I'm missing a simpler solution.

A:

You should never be calling this.setState more than once in a given thread of execution within a component.
So you have a couple of options:
Use forceUpdate instead of setState
You don't HAVE to use this.setState - you can modify the state directly and use this.forceUpdate after you're done.
The main thing to remember here is that you should treat this.state as tainted as soon as you start modifying it directly.  IE: don't use the state, or properties you know you've modified until after you've called this.forceUpdate.  This isn't usually a problem.
I absolutely prefer this method when, you're dealing with nested objects within this.state.  Personally I'm not a huge fan of React.addons.update because I find the syntax extremely clunky.  I prefer to modify directly and forceUpdate.
Create an object that you pass around until finally using it in setState
Collect an object of all your changes, to pass to this.setState at the end of your thread of execution.

