Skip to content

Instantly share code, notes, and snippets.

@hacker0limbo
Forked from sergiodxa/nested-reducers.js
Created September 20, 2021 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hacker0limbo/b67479a8455cd4c4331b8ed26cb2f6d2 to your computer and use it in GitHub Desktop.
Save hacker0limbo/b67479a8455cd4c4331b8ed26cb2f6d2 to your computer and use it in GitHub Desktop.
An example of how to use nested reducers in Redux
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',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment