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.