Skip to content

Instantly share code, notes, and snippets.

@fdaciuk
Created September 17, 2017 00:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fdaciuk/dd06e02a506318251cf1e7a37983d5d5 to your computer and use it in GitHub Desktop.
Save fdaciuk/dd06e02a506318251cf1e7a37983d5d5 to your computer and use it in GitHub Desktop.
Less boilerplate when create a new reducer on Redux

Create Reducer

Less boilerplate when create a new reducer on Redux

Method:

'use strict'

const createReducer = (initialState, actionHandlers) => {
  return (state = initialState, action) => {
    return actionHandlers.hasOwnProperty(action.type)
      ? actionHandlers[action.type](state, action)
      : state
  }
}

export default createReducer

Usage:

'use strict'

import { ADD_COUNTER, REMOVE_COUNTER, INCREMENT, DECREMENT } from './actions'
import createReducer from '../create-reducer'

export const initialState = []

export default createReducer(initialState, {
  [ADD_COUNTER]: (state, action) => state.concat(0),
  [REMOVE_COUNTER]: (state, action) => state.filter((_, i) => i !== action.index),
  [INCREMENT]: (state, action) => state.map((c, i) => i === action.index ? c + 1 : c),
  [DECREMENT]: (state, action) => state.map((c, i) => i === action.index ? c - 1 : c)
})
@suissa
Copy link

suissa commented Sep 17, 2017

Ahhhhhh eles tem q se acostumr a nao usar uhauhauhiaiuhuha

Mas ficou lindo man! Congratz!

@fdaciuk
Copy link
Author

fdaciuk commented Sep 17, 2017

Valeu :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment