rcr

redux-create-reducer

Publishing createReducer from http://redux.js.org/docs/recipes/ReducingBoilerplate.html#generating-reducers

Showing:

Popularity

Downloads/wk

11.4K

GitHub Stars

87

Maintenance

Last Commit

1yr ago

Contributors

10

Package

Dependencies

0

Size (min+gzip)

0.3KB

License

MIT

Type Definitions

Built-In

Tree-Shakeable

No?

Categories

Readme

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)

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial