Skip to content

Instantly share code, notes, and snippets.

@tasandberg
Last active January 14, 2018 18:02
Show Gist options
  • Save tasandberg/cbbc2c3769c163d6c86df1d36ba3fc9f to your computer and use it in GitHub Desktop.
Save tasandberg/cbbc2c3769c163d6c86df1d36ba3fc9f to your computer and use it in GitHub Desktop.
combineReducers for Immutable.js and Redux
// combineReducers.js
function combineReducers(reducers) {
return function(state, action) {
return Object.entries(reducers).reduce((state, [subtree, reducer]) => {
return state.update(subtree, reducer(action))
}, state)
}
}
// reducers.js
// Given a state tree of the following shape
// fromJS({
// user: {
// username: 'Bill'
// },
// posts: {
// 1: { /* ..post 1 data.. */ },
// 2: { /* ..post 2 data.. */ }
// }
// })
// Note that the function name is exactly the same as the state subtree that it handles
function user(action) {
return function(state) {
switch (action.type) {
case SET_USERNAME:
return state.set('username', action.username)
default:
return state
}
}
}
function posts(action) {
return function(state) {
switch (action.type) {
case DELETE_POST:
return state.delete(action.postId)
default:
return state
}
}
}
export default combineReducers({ user, posts })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment