Search code examples
typescriptreduxredux-toolkit

Using sync thunk with redux toolkit


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?


Solution

  • 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))
    }