redux Asynchronous Data Flow Using redux-thunk with jQuery.ajax

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

const loadUser = userId => dispatch => {
    dispatch({ type: 'USER_LOADING' });
    $.ajax('/users/' + userId, {
        type: 'GET',
        dataType : 'json'
    }).done(response => {
        dispatch({ type: 'USER_LOADED', user: response });
    }).fail((xhr, status, error) => {
        dispatch({ type: 'USER_LOAD_ERROR', status, error });
    });
};

To use, dispatch like any other action creator:

store.dispatch(loadUser(123));

This will result in an initial USER_LOADING action being dispatched, which can be used to display a loading indicator (if so desired), and after the response has been received either a USER_LOADED action or USER_LOAD_ERROR action will be dispatched, depending on the result of the $.ajax request.



Got any redux Question?