Search code examples
javascriptreduxreact-reduxredux-thunkredux-toolkit

How to use Redux Toolkit createListenerMiddleware with TypeScript?


Problem

I am using Redux Toolkit and TypeScript to create a Todos app. I want to create middleware that will listen for a dispatched action so I can then dispatch async actions.

What I have so far

// listenerMiddleware.ts
import { createListenerMiddleware, addListener } from '@reduxjs/toolkit'
import type { TypedStartListening, TypedAddListener } from '@reduxjs/toolkit'

import type { RootState, AppDispatch } from './store'

export const listenerMiddleware = createListenerMiddleware()

export type AppStartListening = TypedStartListening<RootState, AppDispatch>

export const startAppListening =
  listenerMiddleware.startListening as AppStartListening

export const addAppListener = addListener as TypedAddListener<
  RootState,
  AppDispatch
>

const store = configureStore({
  reducer: {
    todos: todosReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})

Question

How do I use the startAppListening and addAppListener objects to listen for a specific action? I can't find any examples.


Solution

  • We do show extensive examples in the API reference page :)

    https://redux-toolkit.js.org/api/createListenerMiddleware

    Generally, it's going to look like this:

    import { todoAdded } from "../features/todos/todoSlice"
    
    startAppListening({
      actionCreator: todoAdded,
      effect: (action, listenerApi) => {
        // whatever logic you want here
      }
    })