Blog>
Snippets

Redux Middleware with TypeScript

Exemplify writing a custom Redux middleware using TypeScript, including proper typing of the middleware's parameters for enhanced code quality and maintainability.
import { Middleware, Dispatch, AnyAction } from 'redux';

/**
 * This is a TypeScript example of a simple logging middleware for Redux.
 * It will log every action that passes through the middleware pipeline.
 */
const loggerMiddleware: Middleware = store => next => action => {
    // Log the current state before the action is dispatched
    console.log('state before dispatch', store.getState());

    // Log the action itself
    console.log('dispatching', action);

    // Dispatch the action to the next middleware or to the reducer if this is the last middleware
    let result = next(action);

    // Log the new state after the action was dispatched
    console.log('state after dispatch', store.getState());

    // Return the result of the dispatch (usually the action itself)
    return result;
};

export default loggerMiddleware;
The provided code represents a TypeScript-based Redux middleware that simply logs actions and state information before and after actions are dispatched. The `loggerMiddleware` constant is declared using Redux's `Middleware` type to ensure correct typing for the parameters 'store', 'next', and 'action'. Then, it prints out the current state, the action being dispatched, and the resultant state after the action passes through the middleware. The function returns the result of forwarding the action to either the next middleware in the chain or the reducer if it's the last middleware.