Blog>
Snippets

Listening for actions in a non-slice file

Demonstrate how to listen for and react to Redux actions in a middleware file using `createListenerMiddleware`.
import { createListenerMiddleware, addListener } from '@reduxjs/toolkit';

// Step 1: Create the listener middleware
const listenerMiddleware = createListenerMiddleware();

// Step 2: Define an action you want to listen for
const myAction = () => ({
  type: 'myActionType',
});

// Step 3: Add a listener for your action
// When 'myAction' is dispatched, the callback will be executed
addListener({
  actionCreator: myAction,
  effect: (action, listenerApi) => {
    // The callback can have side-effects and can dispatch other actions
    console.log('Action received:', action);
  },
});

// Step 4: Export middleware to be applied in the store configuration
export default listenerMiddleware;
This code snippet demonstrates how to create a Redux listener middleware and add a listener that listens for a specific action. The `addListener` function takes an object with an `actionCreator` and an `effect` function. This `effect` function is called when the action returned by the `actionCreator` is dispatched. Here, when `myAction` is dispatched, a console log will show the action received.
import { configureStore } from '@reduxjs/toolkit';
import listenerMiddleware from './pathToYourListenerMiddlewareFile';

// Step 1: Configure the store and apply the listener middleware
const store = configureStore({
  reducer: {
    // your reducers go here
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware()
      .prepend(listenerMiddleware.middleware) // Prepending the listener middleware
});

export default store;
This piece of code shows how to configure a Redux store with the `configureStore` function from Redux Toolkit. It imports the listener middleware created previously and applies it to the store using `getDefaultMiddleware().prepend(listenerMiddleware.middleware)`. This step is necessary to include the listener middleware in the Redux middleware chain.
import { myAction } from './pathToYourActionFile';

// Step 1: Dispatch the action
store.dispatch(myAction());
This code snippet is an example of dispatching the action that the previously set up listener middleware is listening for. When `myAction` is dispatched, the listener's effect function will be executed, resulting in the console log created before.