diff --git a/docs/api/createListenerMiddleware.mdx b/docs/api/createListenerMiddleware.mdx index a805e2ebe9..746831a058 100644 --- a/docs/api/createListenerMiddleware.mdx +++ b/docs/api/createListenerMiddleware.mdx @@ -23,6 +23,44 @@ Listeners can be defined statically by calling `listenerMiddleware.startListenin ### Basic Usage +```js +import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit' +import todosReducer, { todoAdded } from '../features/todos/todosSlice' + +// Create the middleware instance and methods: +const listenerMiddleware = createListenerMiddleware() + +// Add one or more listener entries that look for specific actions. +// They may contain any sync or async logic, similar to thunks. +listenerMiddleware.startListening({ + actionCreator: todoAdded, + effect: async (action, listenerApi) => { + // Run whatever additional side-effect-y logic you want here + + console.log('Todo added: ', action.payload.text) + console.log('State: ', listenerApi.getState()) + + // Dispatch some action: + listenerApi.dispatch({ type: "SOME_TYPE", payload: "SOME_PAYLOAD" }) // You can use action creators of course + + } + }, +}) + +const store = configureStore({ + reducer: { + todos: todosReducer, + }, + // Add the listener middleware to the store. + // NOTE: Since this can receive actions with functions inside, + // it should go before the serializability check middleware + middleware: (getDefaultMiddleware) => + getDefaultMiddleware().prepend(listenerMiddleware.middleware), +}) +``` + +### Extended Usage + ```js import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit' @@ -32,15 +70,12 @@ import todosReducer, { todoDeleted, } from '../features/todos/todosSlice' -// Create the middleware instance and methods const listenerMiddleware = createListenerMiddleware() -// Add one or more listener entries that look for specific actions. -// They may contain any sync or async logic, similar to thunks. listenerMiddleware.startListening({ actionCreator: todoAdded, effect: async (action, listenerApi) => { - // Run whatever additional side-effect-y logic you want here + console.log('Todo added: ', action.payload.text) // Can cancel other running instances @@ -73,16 +108,13 @@ listenerMiddleware.startListening({ }, }) -const store = configureStore({ - reducer: { - todos: todosReducer, - }, - // Add the listener middleware to the store. - // NOTE: Since this can receive actions with functions inside, - // it should go before the serializability check middleware - middleware: (getDefaultMiddleware) => - getDefaultMiddleware().prepend(listenerMiddleware.middleware), -}) +// Add another listener: +listenerMiddleware.startListening({ + actionCreator: todoDelete, + ... +}); + +const store = configureStore(...) ``` ## `createListenerMiddleware`