Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Created April 10, 2016 09:38
Show Gist options
  • Save sergiodxa/444b6efdbfa4c604df5b1f1017a61cea to your computer and use it in GitHub Desktop.
Save sergiodxa/444b6efdbfa4c604df5b1f1017a61cea 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',
});
@jbowen28
Copy link

jbowen28 commented Apr 1, 2020

So, what would you have in your store after the last 2 dispatches?

@sergiodxa
Copy link
Author

@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