Home > Net >  Using sync thunk with redux toolkit
Using sync thunk with redux toolkit

Time:04-28

I am used to redux toolkit createAsyncThunk but recently I wanted to make a thunk to group two dispatch calls, like so:

const askQuestion = (q: string) => (dispatch: any, getState: any) => {
    dispatch(setQuestion(q))
    dispatch(fetchAnswer(q))
}

I just want to call one dispatch after another in something like a function to avoid repeating code. I think the best way to do that is to use a thunk.

The problem is that I don't know how to use a thunk that is not async with redux-toolkit. Also, I use typescript and I would like my code strongly typed (I already have types for AppDispatch for instance).

What is the best way to achieve what I want?

CodePudding user response:

Your example thunk that you wrote is correct, as far as the JS code goes.

To get it correctly typed at the TS level, follow the examples we have in the Redux core docs "TS Usage: Thunks" section:

// app/store.ts
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  AnyAction
>

// any other file

const askQuestion = (q: string): AppThunk => (dispatch, getState) => {
    // now `dispatch` and `getState` have the right types
    dispatch(setQuestion(q))
    dispatch(fetchAnswer(q))
}

CodePudding user response:

Classic thunks rarely explicitly return anything and just call dispatch a few times, but if you need to wait for the work to be done, you can let the inner function of a thunk return a promise, and then await this promise in your askQuestion combined thunk: https://redux.js.org/usage/writing-logic-thunks#returning-values-from-thunks

Properly typing everything in a classic thunk has been answered in several other SO questions.

  • Related