Blog>
Snippets

Enhancing Reducers with Unknown Action Handling

Augment existing reducers with functionality to handle unknown actions without impacting the handling of known actions.
function enhancedReducer(reducer) {
  // Wrap the original reducer
  return function(state, action) {
    // Check if the action.type is undefined or unknown
    if (action.type === undefined || action.type.startsWith('@@redux/UNKNOWN')) {
      // Return the current state if the action is unknown
      return state;
    }

    // Otherwise, pass the action to the original reducer
    return reducer(state, action);
  };
}
EnhancedReducer function takes an existing reducer as a parameter and returns a new reducer function. The returned function first checks if the action type is undefined or marked as unknown. If the action is unknown, the current state is returned without any changes, meaning the reducer will ignore the unknown action. If the action is recognized, it is handed over to the original reducer.
const initialState = { count: 0 };

// Example of a simple reducer function
function countReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    // No default case, because enhancedReducer will deal with unknown actions
  }
}
This is an example of a simple reducer managing a count state. It responds to 'INCREMENT' and 'DECREMENT' action types to increase or decrease the count, respectively. There's no default case in the switch statement because the enhancedReducer will handle unknown actions gracefully.
const store = Redux.createStore(enhancedReducer(countReducer));

// Dispatching a known action
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // { count: 1 }

// Dispatching an unknown action
store.dispatch({ type: 'UNKNOWN_ACTION' });
console.log(store.getState()); // { count: 1 }
This part of the code sets up a Redux store using the enhanced reducer. It demonstrates dispatching a known action 'INCREMENT', which updates the state, and then dispatching an unknown action 'UNKNOWN_ACTION'. The state remains unchanged after the unknown action due to the enhancedReducer's handling of unknown actions.