Created
April 10, 2016 09:38
-
-
Save sergiodxa/444b6efdbfa4c604df5b1f1017a61cea to your computer and use it in GitHub Desktop.
An example of how to use nested reducers in Redux
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'; | |
function discussionsList(state = {}, { type, payload} = {}) { | |
if (type === 'ADD') { | |
return { | |
...state, | |
[payload.id]: { | |
id: payload.id, | |
author: payload.author.id, | |
content: payload.content, | |
}, | |
}; | |
} | |
return state; | |
} | |
function discussionsFilter(state = '', { type, payload } = {}) { | |
if (type === 'SET_FILTER') { | |
return payload; | |
} | |
return state; | |
} | |
const discussions = combineReducers({ | |
list: discussionsList, | |
filter: discussionsFilter, | |
}); | |
function authors(state = {}, { type, payload } = {}) { | |
if (type === 'ADD') { | |
return { | |
...state, | |
[payload.author.id]: payload.author, | |
}; | |
} | |
return state; | |
} | |
const reducer = combineReducers({ | |
discussions, | |
authors, | |
}); | |
const store = createStore(reducer); | |
store.subscribe(() => { | |
console.log('new state', store.getState()); | |
}); | |
const discussion = { | |
id: 123, | |
author: { | |
id: 456, | |
username: 'sergiodxa', | |
}, | |
content: 'hola mundo', | |
}; | |
console.log('initial state', store.getState()); | |
store.dispatch({ | |
type: 'ADD', | |
payload: discussion, | |
}); | |
store.dispatch({ | |
type: 'SET_FILTER', | |
payload: 'new', | |
}); |
@jbowen28 something like this:
{
authors: {
456: { id: 456, username: "sergiodxa" },
},
discussions: {
filter: "new",
list: {
123: { id: 123, author: 456, content: "hola mundo" }
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, what would you have in your store after the last 2 dispatches?