Blog>
Snippets

Handling Unknown Actions in Middleware

Show how to intercept unknown actions in middleware and log them before passing them to the next middleware or reducers.
const unknownActionMiddleware = store => next => action => {
  // Check if the 'type' property of the action is undefined or not recognized
  if (typeof action.type === 'undefined' || !isKnownAction(action)) {
    // Log the unknown action
    console.warn('Unknown action intercepted:', action);
  }
  // Continue with the next middleware or reducer
  return next(action);
};

// Helper function to determine if an action is known
function isKnownAction(action) {
  // Define known actions
  const knownActions = ['ACTION_ONE', 'ACTION_TWO'];
  // Check if the action type is in the knownActions array
  return knownActions.includes(action.type);
}
This piece of code represents a middleware function `unknownActionMiddleware` that checks if the incoming action is known or unknown. If the action's type is either undefined or not in a predefined list of known actions, it logs a warning message. The `isKnownAction` function is used to check against a list of known actions. The middleware then passes the action to the next handler in the chain, preserving Redux's action flow.