ReactJS AJAX best practice

- 1 answer

Ad

I am currently trying to learn ReactJS and can't really find any consistent documentation (even the official docs look a bit messed up), especially around AJAX, it all seems a bit cobbled together. I've ended up using the JQuery $.get method which seems like a bit of a cheat.

I have the code below but just wondered if there was a cleaner way of dealing with simple AJAX calls? I'm also firing this off within componentDidMount which seemed the most logical, looking at the lifecycle.

Any help is welcomed!!

getInitialState: function () {
    return {
        numberOfItems: 0,
        items: []
    };
},

componentDidMount: function () {

    $('#MyContainer .loading').show();

    $.get(this.props.source, function (result) {
            var response = result.response;
            this.setState({
                numberOfItems: response.list.numberOfItems,
                items: response.list
            });
        }.bind(this))
        .done(function () {
            $('#MyContainer.loading').hide();
        });
},

render: function() {
    return(
        //Stuff here
    )
};


ReactDOM.render(
    <RecommendationsList source="/my/api/call/here"/>,
    document.getElementById('MyContainer')
);
Ad

Answer

Ad

React is just the view layer. It doesn't concern itself much with fetching data and leaves that up to you. I use jQuery's AJAX functionality for ease of use but you can really use whatever AJAX library you want.

From the code you have provided, you are doing everything correct. You are waiting for the component to mount componentDidMount.

One note to say about keeping asynchronous JavaScript clean, with multiple callbacks; I would assign the call to a variable.

var request = $.get(this.props.source, function (result) {
    var response = result.response;
    this.setState({
        numberOfItems: response.list.numberOfItems,
        items: response.list
    });
}.bind(this));

Then bind listeners to that variable.

request.done(function () {
    $('#MyContainer.loading').hide();
});
Ad
source: stackoverflow.com
Ad