ApathyBear ApathyBear - 4 months ago 7
Ajax Question

Reactjs: using updated state data (from store) immediately

I am using react with flux.

I have a function in my component that calls executes an action upon click:

onClickEventEdit: function(itemId) {

ScheduleActions.getEventById(itemId) // this ultimately is set into `currentEventById` state

var title = this.state.currentEventById['title'] || ""

console.log(title) // logs nothing
console.log(this.state.currentEventById) //logs empty object {}

// then show modal
$('#eventSelectedModal').modal({show: true});

},


My
ScheduleAction
is an ajax call to retrieve the event information. When the Ajax action is done it updates my store. I am under the impression that it updates my store after the title assignment and logs take place.

How can I access this information after the action is called so I can immediately display the information to the client?

Answer

AJAX calls (technically XMLHttpRequests) are executed asynchronously. That means, your synchronous code will continue running while the HTTP call is still waiting for a response. This results in exactly the behavior you are expecting.

The simplest solution would be to extend your getEventById() method with a callback parameter that is called when the asynchronous call has been completed. You can now move the code that should be executed after the call into the callback, effectively delaying its execution;

onClickEventEdit: function(itemId) {

    ScheduleActions.getEventById(itemId, function() {

        var title = this.state.currentEventById['title'] || ""

        console.log(title) // logs nothing
        console.log(this.state.currentEventById) //logs empty object {}

        // then show modal
        $('#eventSelectedModal').modal({
            show: true
        });
    });
},

For an even cleaner solution, you could look into Promises.