Created
May 24, 2016 21:57
-
-
Save CoryDanielson/b27310151ff26566b12b3eb6a28c566a to your computer and use it in GitHub Desktop.
Redux reducer with dispatch table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const ActionTypes = { | |
| ADD_TODO: 'ADD_TODO', | |
| REMOVE_TODO: 'REMOVE_TODO' | |
| }; | |
| export function addTodo(todo) { | |
| return { type: ActionTypes.ADD_TODO, payload: { todo } }; | |
| } | |
| export function removeTodo(todo) { | |
| return { type: ActionTypes.REMOVE_TODO, payload: { todo } }; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import _ from 'lodash'; | |
| import { ActionTypes } from './actions'; | |
| const INITIAL_STATE = { | |
| todos: [] | |
| }; | |
| const actionHandlers = { | |
| [ActionTypes.ADD_TODO]: (state, action) => { | |
| return Object.assign({}, state, { | |
| todos: state.todos.concat(action.payload.todo) | |
| }) | |
| }, | |
| [ActionTypes.REMOVE_TODO]: (state, action) => { | |
| return Object.assign({}, state, { | |
| todos: _.without(state.todos, action.payload.todo) | |
| }) | |
| } | |
| }; | |
| const todosReducer = (state, action) => { | |
| if (!state) { | |
| return INITIAL_STATE; | |
| } else | |
| if (actionHandlers.hasOwnProperty(action.type)) { | |
| return actionHandlers[action.type](state, action); | |
| } else { | |
| return state; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment