Blog>
Snippets

Implementing a Flag Middleware for Redux

Illustrate the implementation of a Redux middleware that intercepts actions related to feature flags and potentially modifies them or triggers additional side effects.
const { applyMiddleware, createStore } = require('redux');

// Action types
const FLAG_TOGGLE = 'FLAG_TOGGLE';
const FLAG_UPDATE = 'FLAG_UPDATE';

// Sample flag-toggle action creator
const toggleFlag = (flagName, value) => ({
  type: FLAG_TOGGLE,
  payload: { flagName, value }
});

// Middleware that handles flag-related actions
const flagMiddleware = store => next => action => {
  if (action.type === FLAG_TOGGLE) {
    // Add custom logic for feature flags here
    console.log(`Toggling feature flag: ${action.payload.flagName}`);
    // Dispatch a new action with updated flag value
    store.dispatch({
      type: FLAG_UPDATE,
      payload: action.payload
    });
  } else {
    // For non-flag actions, just pass the action on to the next middleware
    return next(action);
  }
};

// Reducer for handling flag state updates (simplified example)
const flagReducer = (state = {}, action) => {
  if (action.type === FLAG_UPDATE) {
    return {
      ...state,
      [action.payload.flagName]: action.payload.value
    };
  }
  return state;
};

// Create store with middleware applied
const store = createStore(
  flagReducer,
  applyMiddleware(flagMiddleware)
);

// Dispatch a sample flag toggle action
store.dispatch(toggleFlag('new-feature', true));
This code snippet describes the implementation of a Redux middleware that intercepts 'FLAG_TOGGLE' actions to perform custom logic related to feature flags. The middleware captures these actions, logs the toggling of a feature flag, and dispatches a new action to update the feature flag's value in the state. A sample flagReducer is also provided to handle the state updates based on the dispatched 'FLAG_UPDATE' actions. Finally, it demonstrates how to create a Redux store with the middleware applied and how to dispatch a sample flag toggle action.