Redux: Proper pattern for Redux actions and promises

Created on 29 Oct 2015  路  2Comments  路  Source: reduxjs/redux

Hi there,

Before Redux, using the standard Flux implementation, I would fire actions that would dispatch results using the Dispatcher and updating the stores.

I would do something like this:

myAsyncAction().then(() => this.setState({updateLocalComponentState: true}));

function myAsyncAction() {
   return new Promise((resolve, reject) => {
      request().then((response) => {
         Dispatcher.dispatch({type: SOME_ACTION, value: response.value});
         resolve(response);
      });
   });
}

If i needed to update my local component state for whatever reason, it was very easy to still dispatch my action but be able to run some code whenever the action was finished.

Now with Redux, I understand that you could have a reducer state that represents the current status of the action (IN_PROGRESS, FINISHED, etc) and then have your component listen to change in props and update the local component state, I understand this pattern and it makes sense.

However, I still wanted to raise the question, a lot of times I find myself wishing I could do the same with redux without having to keep the state of the call in the Redux state, and simply say hey action whenever you are finished, run this function.

I know I can pass a callback to the action that can be ran once the action is finished, but I like promises better.

After discussing with some team members, I decided to post here to get some guidance to see if I was just lazy or if it was indeed "okay" or "still good practice" to use something like redux-promise (https://github.com/acdlite/redux-promise) and have the best of both worlds.

Does all that make sense? Thanks!

Most helpful comment

You can use redux-promise and dispatch promises directly.

You can also use redux-thunk in a similar fashion to what you previously did:

function myAsyncAction() {
   return dispatch => new Promise((resolve, reject) => {
      request().then((response) => {
         dispatch({type: SOME_ACTION, value: response.value});
         resolve(response);
      });
   });
}

dispatch(myAsyncAction()).then(() => this.setState({updateLocalComponentState: true}));

All 2 comments

You can use redux-promise and dispatch promises directly.

You can also use redux-thunk in a similar fashion to what you previously did:

function myAsyncAction() {
   return dispatch => new Promise((resolve, reject) => {
      request().then((response) => {
         dispatch({type: SOME_ACTION, value: response.value});
         resolve(response);
      });
   });
}

dispatch(myAsyncAction()).then(() => this.setState({updateLocalComponentState: true}));

@gaearon nice, makes sense. We are already using redux-thunk so it works out great. Thanks Dan.

Was this page helpful?
0 / 5 - 0 ratings