Skip to content

Instantly share code, notes, and snippets.

@CoryDanielson
Created May 24, 2016 21:57
Show Gist options
  • Select an option

  • Save CoryDanielson/b27310151ff26566b12b3eb6a28c566a to your computer and use it in GitHub Desktop.

Select an option

Save CoryDanielson/b27310151ff26566b12b3eb6a28c566a to your computer and use it in GitHub Desktop.
Redux reducer with dispatch table
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 } };
}
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