@laserware/stasis
    Preparing search index...

    Function createReducer

    • A utility function that allows defining a reducer as a mapping from action type to case reducer functions that handle these action types. The reducer's initial state is passed as the first argument.

      Type Parameters

      • S extends unknown

      Parameters

      • initialState: S | (() => S)

        State | (() => State): The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with undefined as its state value, and is primarily useful for cases like reading initial state from localStorage.

      • mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void

      Returns ReducerWithInitialState<S>

      The body of every case reducer is implicitly wrapped with a call to produce() from the immer library. This means that rather than returning a new state object, you can also mutate the passed-in state object directly; these mutations will then be automatically and efficiently translated into copies, giving you both convenience and immutability.

      This function accepts a callback that receives a builder object as its argument. That builder provides addCase, addMatcher and addDefaultCase functions that may be called to define what actions this reducer will handle.

      import {
      createAction,
      createReducer,
      UnknownAction,
      PayloadAction,
      } from "@reduxjs/toolkit";

      const increment = createAction<number>("increment");
      const decrement = createAction<number>("decrement");

      function isActionWithNumberPayload(
      action: UnknownAction
      ): action is PayloadAction<number> {
      return typeof action.payload === "number";
      }

      const reducer = createReducer(
      {
      counter: 0,
      sumOfNumberPayloads: 0,
      unhandledActions: 0,
      },
      (builder) => {
      builder
      .addCase(increment, (state, action) => {
      // action is inferred correctly here
      state.counter += action.payload;
      })
      // You can chain calls, or have separate `builder.addCase()` lines each time
      .addCase(decrement, (state, action) => {
      state.counter -= action.payload;
      })
      // You can apply a "matcher function" to incoming actions
      .addMatcher(isActionWithNumberPayload, (state, action) => {})
      // and provide a default case if no other handlers matched
      .addDefaultCase((state, action) => {});
      }
      );