Blog>
Snippets

Handling Side Effects with createListenerMiddleware

Create an example that illustrates how to use `createListenerMiddleware` for managing side effects in response to state changes or actions.
import { createListenerMiddleware } from '@reduxjs/toolkit';

// Define the middleware using the `createListenerMiddleware` function
const listenerMiddleware = createListenerMiddleware();

// Here you start listening to the specific actions or state changes
listenerMiddleware.startListening({
  // Let's say we're listening for 'todos/addTodo' action
  actionCreator: todosActions.addTodo,
  // `effect` is the side effect function to run when the action is dispatched
  effect: async (action, listenerApi) => {
    // Side effect logic for 'todos/addTodo', like showing a success message
    console.log(`Todo added: ${action.payload}`);
  }
});

export default listenerMiddleware;
This code snippet creates a listener middleware and sets up a listener for the 'todos/addTodo' action. When the action is dispatched, it runs a side effect that logs a message to the console.