Blog>
Snippets

Conditionally Dispatching Actions Based on State

Illustrate how a custom middleware can analyze the current state before an action is processed and conditionally dispatch another action based on specific state conditions.
const conditionalDispatchMiddleware = store => next => action => {
  // Check if the action is the one we're interested in
  if (action.type === 'CHECK_CONDITION') {
    const currentState = store.getState();
    // Conditionally check the state before proceeding
    if (currentState.someCondition) {
      // Dispatch another action based on specific state condition
      store.dispatch({ type: 'ANOTHER_ACTION' });
    }
  }
  // Pass action to the next middleware or reducer
  return next(action);
};
This middleware intercepts actions of type 'CHECK_CONDITION'. It checks the current state for a specific condition ('someCondition') and conditionally dispatches 'ANOTHER_ACTION' based on that condition. It then passes the action to the next middleware or reducer.
const store = createStore(
  rootReducer,
  applyMiddleware(conditionalDispatchMiddleware)
);
This code snippet shows how to apply the conditionalDispatchMiddleware to the Redux store. It is added to the store creation by using applyMiddleware function from Redux.