2.0.1 • Published 4 years ago

redux-create-reducer v2.0.1

Weekly downloads
9,895
License
MIT
Repository
github
Last release
4 years ago

redux-create-reducer

NPM version Build status Test coverage Downloads

This code packaged as a node module

Usage:

import { createReducer } from 'redux-create-reducer';
import * as ActionTypes from '../constants/ActionTypes';

const initialState = [];

export const todos = createReducer(initialState, {
  [ActionTypes.ADD_TODO](state, action) {
    const text = action.text.trim();
    return [...state, text];
  },

  [ActionTypes.REMOVE_TODO](state, action) {
    return state.filter((_, i) => i !== action.index);
  }

  // All other action types result in state being returned
})

Typescript typings

This library also provides powerful typescript typings when using Action classes:

interface Action {
  type: string;
}

interface State {
  value: number;
}

class Reset implements Action {
  readonly type = 'Reset Action';
}
class AddOne implements Action {
  readonly type = 'AddOne Action';
}
class AddCustom implements Action {
  readonly type = 'AddCustom Action';
  constructor(public readonly value: number) { }
}

type Actions = Reset | AddOne | AddCustom;

const reducer = createReducer<State, Actions>({ value: 0 }, {
  'Reset Action': (state, action) => ({ value: 0 }),
  'AddOne Action': (state, action) => ({ value: state.value + 1 }),
  'AddCustom Action': (state, action) => ({ value: state.value + action.value }),
});

// If you wanted to exclude some actions you can use the `Exclude` type.
type ActionsWithoutAddOne = Exclude<Actions, AddOne>
const reducerThatDoesNotHandleAddOne = createReducer<State, ActionsWithoutAddOne>({ value: 0 }, {
  'Reset Action': (state, action) => ({ value: 0 }),
  'AddCustom Action': (state, action) => ({ value: state.value + action.value }),
});

Stackblitz

Removing 'Reset Action': (state, action) => ({ value: 0 }), in the reducer causes the error: Property '"Reset Action"' is missing in type .... Similarly, adding 'Nonexisting Action': (state, action) => ({ value: 0 }), causes the type error: Object literal may only specify known properties, and ''Nonexisting Action'' does not exist in type 'Handlers<State, Actions>'.ts(2345)