Blog>
Snippets

Fallback Reducer for Unknown Actions

Define a fallback reducer that handles all unknown actions and updates the state in a controlled manner, possibly alerting about the unhandled action.
function fallbackReducer(state = {}, action) {
  // Check if the action type is unrecognized
  if (typeof action.type === 'undefined' || action.type === 'UNHANDLED_ACTION') {
    // Optionally, log a warning or alert
    console.warn('Unhandled action:', action);
    // Return the current state without modifications
    return state;
  }
  // Handle other actions or delegate to other reducers
  switch (action.type) {
    // ... other action handlers
    default:
      // Return the current state by default if action is known
      return state;
  }
}
This piece of code represents a 'fallbackReducer' function. When the action type is undefined or recognized as 'UNHANDLED_ACTION', it logs a warning and returns the current state without making any changes, effectively ignoring the action. For all other known actions, it would go into the switch statement to be handled appropriately. If the action type does not match any case, it once again returns the current state unchanged.