cyberwombat
cyberwombat

Reputation: 40074

Calling dispatch inside redux middleware

I am trying to integrate redux-simple-auth in my existing reudx API. My old implementation used the native fetch and I added headers etc.. This new module provides a fetch replacement however it returns a redux action and am having a bit of a struggle figuring out how to set things up.

My store:

function configureStore (initialState) {
  const middlewares = [
    authMiddleware,  // This is from rediux-simple-auth
    apiMiddleware, // My own middleware
    thunk

  ]

  const store = createStore(rootReducer, initialState, compose(
    applyMiddleware(...middlewares), getInitialAuthState({ storage }))
  )
}

My middleware simplified:

import { fetch } from 'redux-simple-auth'
export default store => next => action => {      
  ...
  next(my start action...)
  return store.dispatch(fetch(API_ROOT + endpoint, { method }))  
    .then(response => {
       next(my success/fail action...)
    })

}

When I run this I can see my start and fail actions in redux inspector but not the fetch one (which does trigger a FETCH one)

If I call next instead of store.dispatch then it works in the sense that it tiggers the action but it does not return a promise I cannot get results.

How can I fix this flow?

Upvotes: 2

Views: 2379

Answers (1)

Sylvain
Sylvain

Reputation: 19249

next is not dispatch. Try this:

export default ({dispatch}) => next => action => ...

Use dispatch to dispatch your new action and use next(action) to pass the original action to the next middleware.

Upvotes: 8

Related Questions