पाठ 15 / 25
Middleware and Redux DevTools
Intercept actions and inspect history.
The dispatch pipeline
Middleware wraps dispatch: each one receives the store API, the next function and the action, and can log, transform, delay or block actions before they reach reducers. Thunks, RTK Query and the listener middleware are all middleware. In Redux Toolkit 2 the action parameter is typed unknown, so narrow it with an action creator's .match() or isAction. Redux DevTools shows every action, the state after it and a diff, and supports jumping between states (time travel), which makes Redux bugs unusually easy to trace.
A small analytics middleware
Typed with Middleware and .match().
import type { Middleware } from '@reduxjs/toolkit';
import { itemAdded } from './features/cart/cartSlice';
export const analytics: Middleware = (storeApi) => (next) => (action) => {
const result = next(action); // let reducers run first
if (itemAdded.match(action)) {
track('add_to_cart', { id: action.payload.id, qty: action.payload.qty });
}
return result;
};
// store.ts
// middleware: (gDM) => gDM().concat(analytics)Keep secrets out of DevTools
Anything in state or actions is visible in DevTools. Avoid storing tokens there, or use the devTools options (such as sanitisers) in production builds; check the docs for your version.
त्वरित जाँच: In Redux Toolkit 2, how should custom middleware check an action type safely?
- Use an action creator's .match(action) or isAction
- Cast action to any
- Compare action.name
- Read action from getState
Answer
Use an action creator's .match(action) or isAction — The action parameter is unknown and must be narrowed.