Battle_Slug
Battle_Slug

Reputation: 2105

Store fetched data to avoid fetching it with each reload of the component

I have a React component that is supposed to be used in different views. This component is Select element with pretty long list of options, and I load this list from db via ajax call. For all views used the same Select with the same list of options. My problem is that I don't understand how to coerce this Select to load this list only once, and reuse it for other renderings. It looks somewhat like this now (simplistically, obviously):

var SelectField = React.createClass({
        loadListFromServer: function () {...}
        getInitialState()
        {
            return {
                options: [],
            };
        },

        componentDidMount() {
            this.setState({
                options: this.loadListFromServer()
            });
        },

        render: function () {
          return (
          <div>
             <Select options={this.state.options} />
          </div>
            );
        }
    })
    ;

var Index = React.createClass({
    render: function () {
        return (
                    <SelectField />
        );
    }
});

var Content = React.createClass({
    render: function () {
        return (
                    <SelectField />
        );
    }
});

    ReactDOM.render(
        <Router history={createBrowserHistory()}>
            <Route path="/" component={Index}/>
            <Route path="path" component={Content}/>
        </Router>,
        document.getElementById("container")
    )

What I tried to do: make both options and loadListFromServer() global and call the loadListFromServer() from window.init. Then Index renders with empty options as it is being filled when everything is already mounted. So what is general approach to achieve it? Thanks, and I am sorry if my question is stupid - I've just started this topic.

Upvotes: 1

Views: 76

Answers (1)

escargot agile
escargot agile

Reputation: 22389

When you say you only want to load the <Select> component once, I assume you mean you only want to load its data once.

You might try a flux architecture that separates components from actions.

The root of the problem in your example seems to be the tight coupling between the <Select> component and the state that it presents (the list of options). Every time the component is used, it must create its state or reuse the state from a different instance of <Select>. But in the latter case we would need somewhere to store the state between different instances of the component.

Have you looked into redux? It decouples the state from components.

Upvotes: 1

Related Questions