Created
December 9, 2015 20:11
-
-
Save brumm/9b9ce62a550e8cf83fc1 to your computer and use it in GitHub Desktop.
redux genericReducer
This file contains 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 {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) |
This file contains 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
// 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