Blog>
Snippets

Using Redux Middleware with Typed Actions

Demonstrate how to write custom middleware for Redux that operates on typed actions instead of AnyAction.
// Define a custom action type
interface MyAction {
  type: 'MY_ACTION_TYPE';
  payload: string;
}

// Custom middleware that only operates on MyAction
const myMiddleware: Middleware<{}, any, Dispatch<MyAction>> = store => next => action => {
  // Check if the action is the right type
  if (action.type === 'MY_ACTION_TYPE') {
    console.log('Payload for MY_ACTION_TYPE:', action.payload);
    // Perform some middleware logic here...
  }
  // Continue to the next middleware or reducer
  return next(action);
};
This code defines a custom action interface (MyAction) with a type and payload. The myMiddleware function is an example of a Redux middleware that checks if the incoming action is of type 'MY_ACTION_TYPE', then logs its payload and optionally performs some logic before passing the action to the next middleware or reducer.
// Another example with a typed action
interface AnotherAction {
  type: 'ANOTHER_ACTION_TYPE';
  data: number;
}

// Middleware that operates on AnotherAction
const anotherMiddleware: Middleware<{}, any, Dispatch<AnotherAction>> = ({ dispatch }) => next => action => {
  if (action.type === 'ANOTHER_ACTION_TYPE') {
    // Handle the action or dispatch another action
    dispatch({ type: 'ANOTHER_ACTION_RESULT', data: action.data * 2 });
  }
  return next(action);
};
This code snippet showcases another middleware definition, this time for actions of type 'ANOTHER_ACTION_TYPE'. It intercepts actions of that type, processes the data (e.g., doubling it), and dispatches a new action with modified data.
// Applying the middleware to the Redux store
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';

// Combine your middleware into an array
const middlewares = [myMiddleware, anotherMiddleware];

// Create a Redux store and apply the middleware
const store = createStore(
  rootReducer,
  applyMiddleware(...middlewares)
);
This final piece of code demonstrates how to import the `createStore` and `applyMiddleware` functions from Redux, combine the custom middlewares into an array, and finally create the Redux store with the `rootReducer` and the array of middlewares.