Blog>
Snippets

Refactoring Legacy Middleware to Utilize Action Matchers

Show the process of refactoring an existing JavaScript Redux middleware to use Redux Toolkit's action matchers for more concise and clear action type handling, improving code readability and maintainability.
import { createAction, Middleware } from '@reduxjs/toolkit';

// Example of an action creator with Redux Toolkit
const fetchSuccess = createAction('FETCH_SUCCESS');
const fetchFailure = createAction('FETCH_FAILURE');

// Legacy middleware that uses a switch statement to handle actions
const legacyMiddleware = store => next => action => {
  switch (action.type) {
    case 'FETCH_SUCCESS':
      // Handle fetch success
      break;
    case 'FETCH_FAILURE':
      // Handle fetch failure
      break;
    default:
      next(action);
  }
};

// Refactored middleware that uses action matchers
const refactoredMiddleware = store => next => action => {
  if (fetchSuccess.match(action)) {
    // Handle fetch success
  } else if (fetchFailure.match(action)) {
    // Handle fetch failure
  } else {
    next(action);
  }
};
This refactored middleware replaces the switch statement with the match method provided by the action creators from Redux Toolkit. This approach ensures that actions are checked against the precise types they were created with, improving type safety and reducing the likelihood of runtime errors.