Leo Selig
Leo Selig

Reputation: 1071

How to handle data changes in Flux/React?

So far I worked quite thoroughly through the two official Flux architecture examples (https://github.com/facebook/flux).

However, I am really unsure of how you would accomplish a change of data after the initial data has been rendered.

For instance, imagine a todo item changes in the example because of a server response, how would that be implemented to have the according item updating correctly without using setProps() in the item component (which is, as far as I understood, prohibited)?

This might be more of React-related misunderstanding - looking forward to your suggestions!

Upvotes: 4

Views: 3818

Answers (1)

Mike Driver
Mike Driver

Reputation: 8511

The idea with flux is that you set your React component's internal state (or part of it) to an object or value from a store every time that store changes.

So for example something like this (not real code, but to give you an idea):

var Component = react.createClass({
    getInitialState: function() {
        return { 
            items: Flux.getStore("ItemStore").getItems()
        }
    },

    componentDidMount: function() {
        this.store = Flux.getStore("ItemStore");
        this.store.addChangeListener(this.onStoreChange)
    },

    componentWillUnmount: function() {
        this.store.removeChangeListener(this.onStoreChange);
    },

    onStoreChange: function() {
        this.setState({
            items: this.store.getItems()
        });
    },

    render: function() {

        var items = [];
        for (var i = 0; i < this.state.items; i++) {
            items.push(
                <li key={i}>{this.state.items[i]}</li>
            );
        }

        return (
            <ul>{items}</ul>
        );
    }
});

What this example component does is render a list of this.state.items that reside in a store called ItemStore and are accessed by ItemStore.getItems(). So take a look at the componentDidMount which gets the store, binds a callback to whenever the store is changed onStoreChange and then sets the current component state of items to the items array provided by store.getItems().

As a result when the component is first mounted it gets the current items from the store and displays them, whenever the store changes it will execute onStoreChange which gets the items again from the store and sets them again via this.setState().

Naturally we want to be clean so this component also removes the onStoreChange binding when the component is being unmounted.

Note: Remember that calling this.setState() inside componentDidMount does not cause a component re-render :)

More on this in the facebook-flux documentation here: http://facebook.github.io/flux/docs/todo-list.html#listening-to-changes-with-a-controller-view

Upvotes: 5

Related Questions