[SOLVED] Redux toolkit dispatch action with dispatch and getState as arguments, same as simple redux implementation with function enhancer

Issue

This Content is from Stack Overflow. Question asked by Dishant Chavda

I have been using simple redux with this function enhancer for a long time :

const asyncFunctionMiddleware = storeAPI => next => action => {
  // If the "action" is actually a function instead...
  if (typeof action === 'function') {
    // then call the function and pass `dispatch` and `getState` as arguments
    return action(storeAPI.dispatch, storeAPI.getState)
  }

  // Otherwise, it's a normal action - send it onwards
  return next(action)
}

Once this was added to applyMiddleware at time of store create you can simply use it as this :

// Write a function that has `dispatch` and `getState` as arguments
const stateBasedLotOfDispatches = (dispatch, getState) => {
  // Lot of conditions based on current state -> getState
  // get arguments to pass to action1
  // create payload for action2
  dispatch(action1())
  dispatch(action2())
  ...
}

I searched a lot about how to do this with redux toolkit, but could not find a way or maybe missing something basic about redux-toolkit and will like someone to point me in the right direction.

Need to add 1 more thing, function called will not be asyncThunk type so i don’t need it to be async.



Solution

That is literally the redux-thunk middleware, and that one is already enabled automatically with Redux Toolkit.

You can just go ahead and dispatch(stateBasedLotOfDispatches) and it will work.


This Question was asked in StackOverflow by Dishant Chavda and Answered by phry It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?