Blog>
Snippets

Extending Store Features with UnknownAction

Discuss how to use UnknownAction as an extension point to add features to the Redux store, such as undo/redo functionality.
function unknownActionMiddleware(store) {
  return function(next) {
    return function(action) {
      const prevState = store.getState();
      const result = next(action);
      // If the action is not recognized, log it for potential feature extension
      if (action.type === 'UNKNOWN_ACTION') {
        console.warn('An unknown action was dispatched:', action);
      }
      // Your logic to handle unknown actions, like storing previous state for undo
      return result;
    };
  };
}
This is a Redux middleware that captures every action dispatched to the store. If an action has a type of 'UNKNOWN_ACTION', it is logged to the console, and here you can add additional logic to handle such unknown actions, which could include storing the state for an undo feature.
// Reducer example
function appReducer(state = {}, action) {
  switch (action.type) {
    // Your existing handlers
    default:
      // Modify the action type to 'UNKNOWN_ACTION' if not recognized
      return {...state, lastUnknownAction: action.type === 'UNKNOWN_ACTION' ? action : state.lastUnknownAction};
  }
}
This is an example reducer that includes a case to handle the 'UNKNOWN_ACTION'. It adjusts the state by recording the last unknown action; this can be helpful for extending store features such as implementing custom logic for undo/redo based on unknown actions.
// Adding the middleware to your Redux store
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  applyMiddleware(unknownActionMiddleware)
);
This code shows how you would apply the unknownActionMiddleware to your Redux store during its creation. By calling `applyMiddleware`, the middleware will be included in the Redux store's operation, ready to capture and handle unknown actions.