user2069136
user2069136

Reputation: 289

Middleware that runs BEFORE any slice action/reducer?

In my React Redux-Toolkit app, I want a way to check some data before any slice action update is happening. Is there any way to do this? I know there's the createListenerMiddleware but, as far as I know, they always run after the action has been executed and data in store has been updated.

Upvotes: 0

Views: 67

Answers (1)

Drew Reese
Drew Reese

Reputation: 202721

In my React Redux-Toolkit app, I want a way to check some data before any slice action update is happening. Is there any way to do this?

Yes, you can create a custom middleware. See Understanding Redux: Middleware for full details.

Example implementation:

export const sampleMiddleware = (store) => (next) => (action) => {
  // Logic to run before the next action is processed and reducers update the store
  console.log(
    "before action/reducer",
    JSON.stringify({ action, state: store.getState() })
  );

  // Process the next action
  const result = next(action);

  // Logic to run after the action is processed and reducers updated the store
  console.log(
    "after action/reducer",
    JSON.stringify({ result, state: store.getState() })
  );

  // Return the result of processing action
  return result;
};

Add your custom middleware to the store when creating it.

import { configureStore } from "@reduxjs/toolkit";
...
import { sampleMiddleware } from "./sample.middleware";

const store = configureStore({
  reducer: ...,
  middleware: (getDefaultMiddleware) => 
    getDefaultMiddleware().concat(sampleMiddleware),
});

Demo

Edit summer-sound

enter image description here

Upvotes: 0

Related Questions