简体   繁体   中英

Dispatch multiple action in redux middleware

I have this React Native app along with redux where all HTTP requests are performed through async actions using redux-promise-middleware .

Now I want to handle every error that can be sent by the API and for that I'm implementing a redux middleware that will intercept every action with the type XXX_REJECTED (since redux-promise-middleware dispatches a _REJECTED action when an async action fails).

But now I have this problem... In the middleware I want to be able to dispatch a new action (a API_ERROR for instance) and still be able to perform next() for the original action (the XXX_REJECTED ).

Here's my middleware:

export default ({ dispatch }) => next => (action) => {
  if (action.type.match(/w*(_REJECTED)/)) {
    dispatch({
      type: 'API_ERROR',
      payload: action.payload,
    })
  }

  next(action)
}

But with this code once the new action is dispatched, the next() is never executed.

Does this make sense? Is it possible to dispatch multiple actions in a middleware?

I think you need to return the next action. And yes you should be able to dispatch as many actions as you want.

return next(action)

Found that everything was ok with the middleware. You can dispatch as many actions as you wish.

My mistake was in the reducer, where I had a case with no state returned from it (only a console.log(action) ).

My bad!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM