Blog>
Snippets

Conditional Middleware Execution in Redux v5.0.0

Provide an example of how to conditionally execute middleware based on certain criteria in the actions or state.
import { createStore, applyMiddleware } from 'redux';

// A simple reducer
const reducer = (state = {}, action) => {
  switch (action.type) {
    case 'ACTION_ONE':
      return { ...state, data: action.data };
    default:
      return state;
  }
};

// Middleware that only runs for a specific action type
const conditionalMiddleware = store => next => action => {
  // Check the action type
  if (action.type === 'ACTION_ONE') {
    // Run some code if the condition is met
    console.log('conditionalMiddleware triggered:', action);
    // Modify the action or perform side effects here
  }
  return next(action);
};

// Create the Redux store with the conditional middleware applied
const store = createStore(reducer, applyMiddleware(conditionalMiddleware));
This JavaScript code creates a Redux store with a simple reducer and a middleware that conditionally executes code only when the dispatched action is of type 'ACTION_ONE'. The `conditionalMiddleware` function intercepts every action, but only logs the action to the console and could perform additional logic if the action type matches 'ACTION_ONE'. Afterwards, the action is passed along to the next middleware or reducer with `next(action)`.