Blog>
Snippets

Conditional State Updates with createReducer

Showcase the use of conditional logic inside createReducer to perform different state updates based on the action payload content.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Define action creators
const increment = createAction('increment');
const decrement = createAction('decrement');
const multiply = createAction('multiply');

// Initial state
const initialState = 0;

// Reducer function with conditional logic based on action payload
const counterReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(increment, (state, action) => state + 1)
    .addCase(decrement, (state, action) => state - 1)
    .addCase(multiply, (state, action) => {
      // Check if payload is a number and is not zero, then multiply
      if (typeof action.payload === 'number' && action.payload !== 0) {
        return state * action.payload;
      }
      // If payload is zero, return state without changes
      return state;
    });
});
This JavaScript code sets up a Redux reducer with conditional state updates using the Redux Toolkit's `createReducer` function. It defines three actions: increment, decrement, and multiply. The reducer listens for these actions and updates the state accordingly. When the multiply action is dispatched, there is a check for the payload to ensure it is a number and not zero before performing multiplication. If the payload fails these checks, the state remains unchanged.