Redux thunk: return a promise from a submitted action

Is it possible to return a promise / signal from the creator of the action allowed when Redux thunk successfully sent a specific action?

Consider the action creator:

function doPost(data) { return (dispatch) => { dispatch({type: POST_LOADING}); Source.doPost() // async http operation .then(response => { dispatch({type: POST_SUCCESS, payload: response}) }) .catch(errorMessage => { dispatch({type: POST_ERROR, payload: errorMessage}) }); } } 

I want to call some function asynchronously in the component after calling the creator of the doPost action when Redux either sent POST_SUCCESS or POST_ERROR. One solution would be to pass the callback to the creator of the action itself, but that would make the code dirty and difficult to understand and maintain. I could also query the state of Redux during the loop, but that would be inefficient.

Ideally, the solution would be a promise that would allow / reject when certain actions are sent (in this case, POST_SUCCESS or POST_ERROR).

 handlerFunction { doPost(data) closeWindow() } 

The above example should be reorganized, so closeWindow () is only called when doPost () is successful.

+5
source share
1 answer

Of course, you can return a promise from an asynchronous action:

 function doPost(data) { return (dispatch) => { dispatch({type: POST_LOADING}); // Returning promise. return Source.doPost() // async http operation .then(response => { dispatch({type: POST_SUCCESS, payload: response}) // Returning response, to be able to handle it after dispatching async action. return response; }) .catch(errorMessage => { dispatch({type: POST_ERROR, payload: errorMessage}) // Throwing an error, to be able handle errors later, in component. throw new Error(errorMessage) }); } } 

Now the dispatch function returns a promise:

 handlerFunction { dispatch(doPost(data)) // Now, we have access to `response` object, which we returned from promise in `doPost` action. .then(response => { // This function will be called when async action was succeeded. closeWindow(); }) .catch(() => { // This function will be called when async action was failed. }); } 
+7
source

All Articles