redux-create-reducer
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

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)

Readme

Keywords

Package Sidebar

Install

npm i redux-create-reducer

Weekly Downloads

7,013

Version

2.0.1

License

MIT

Unpacked Size

9.37 kB

Total Files

7

Last publish

Collaborators

  • kolodny
  • gajus