Skip to content

Instantly share code, notes, and snippets.

@brumm
Created December 9, 2015 20:11
Show Gist options
  • Save brumm/9b9ce62a550e8cf83fc1 to your computer and use it in GitHub Desktop.
Save brumm/9b9ce62a550e8cf83fc1 to your computer and use it in GitHub Desktop.
redux genericReducer
import {combineReducers, createStore} from "redux";
import todosActions from './actions/todos'
const genericReducer = (storeName, initialState = null, actions = {}) => {
return {
[storeName]: (state = initialState, action) => {
if (action.type === 'HYDRATE' && action.data[storeName])
return action.data[storeName]
let handler = actions[action.type]
return handler ? handler(state, action) : state
}
}
}
const rootReducer = combineReducers({
...genericReducer('users' , []),
...genericReducer('todos' , [], todosActions.handlers)
})
export default initialState => createStore(rootReducer, initialState)
// actions/todos/index.js
const handlers = {
ADD_TODO(state, {todo}) {
return [...state, todo]
}
}
const creators = {
addTodo(todo) {
return {
type: 'ADD_TODO',
todo
}
}
}
export default {
handlers,
creators
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment