Pacote
    Preparing search index...

    Function reducerFromState

    • Creates a reducer with an initial state and no handlers.

      Chain .on() calls to register one or more action creators and their corresponding state update handlers.

      Type Parameters

      • S

        State type.

      Parameters

      • initialState: S

        State used when the reducer receives undefined.

      Returns EnhancedReducer<S>

      A reducer with an .on() method for adding typed handlers.

      import { createAction, reducerFromState } from '@pacote/flux-actions'

      const person = createAction<{ name: string }>('PERSON')
      const dog = createAction<{ name: string }>('DOG')
      const car = createAction<{ brand: string }>('CAR')

      const reducer = reducerFromState({ now: 'None', then: '' })
      .on([person, dog], (state, action) => ({
      now: action.payload.name,
      then: state.now,
      }))
      .on(car, (state, action) => ({
      now: action.payload.brand,
      then: state.now,
      }))

      const s2 = reducer(undefined, person({ name: 'Marty McFly' }))
      // { now: 'Marty McFly', then: 'None' }
      const s3 = reducer(s2, dog({ name: 'Einstein' }))
      // { now: 'Einstein', then: 'Marty McFly' }
      const s4 = reducer(s3, car({ brand: 'DeLorean' }))
      // { now: 'DeLorean', then: 'Einstein' }

      Reducing actions with errors wrapped in Either can store the error in state while handling a successful payload:

      import { type Either, tryCatch } from 'fp-ts/lib/Either'

      type State = { year: number; error?: Error }
      const changeYear = createAction<Either<Error, number>>('CHANGE_YEAR')
      const reducer = reducerFromState<State>({ year: 1985 }).on(
      changeYear,
      (state, { payload }) =>
      payload.fold(
      (error) => ({ ...state, error }),
      (year) => ({ year, error: undefined }),
      ),
      )

      reducer(undefined, changeYear(tryCatch(() => 2025, (error) => error as Error)))