Phoelpis Phoelpis - 11 days ago 5
React JSX Question

React Js: How to reload the initial data loaded via ajax?

I get my initial data from an outside JSON in

componentDidMount: function() { .... $.get(jsonfile, function(data) { ....


But the state of "jsonfile" changes via an input.
When the state of "jsonfile" prop changes the render method is invoked again, but I will also want to re-run the
$.get
request.
What would be the proper (
react
) way to do it?

Answer

You should abstract away your data fetching. If you put your fetching of data in a separate helper method you can call that method when needed, and it should do the fetching (and later updating) of the state

React.createClass({
    componentDidMount: function () {
        this.fetchData();
    },

    fetchData: function () {
        var _this = this;
        $.get('....', function (result) {
            _this.setState(result);
        });
    },

    handleClick: function () {
        this.fetchData();
    },

    render: function () {
        return (<div onClick={this.handleClick}>{data}</div>);
    },
});