user2997932
user2997932

Reputation: 127

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?

Upvotes: 3

Views: 2569

Answers (2)

damm123
damm123

Reputation: 41

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)

Upvotes: 2

user2997932
user2997932

Reputation: 127

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!

Upvotes: 0

Related Questions