Skip to content

Instantly share code, notes, and snippets.

@laytong
Created August 30, 2016 23:56
Show Gist options
  • Save laytong/19b20dd02963d9b71ee5ef1ec87815d2 to your computer and use it in GitHub Desktop.
Save laytong/19b20dd02963d9b71ee5ef1ec87815d2 to your computer and use it in GitHub Desktop.
Nested reducer pattern for deeply nested state
const defaultState = {
person: {
name: ''
age: 20,
friends: []
pets: []
}
}
const actionMap = {
'UPDATE_NAME': function(state, action){
return {...state, name: action.name};
},
'UPDATE_PET': function(state, action){
const pets = PetsReducer(state.pets, action)
return(...state, pets); // Or use the update(state, {pets: {$set: pets}});
}
}
export const PersonReducer = function (state = defaultState, action) {
if (actionMap[action.type]) {
return actionMap[action.type](state, action);
} else {
return state;
}
};
export default PersonReducer;
const petsActionMap = {
'UPDATE_PET': function(state, action){
return state.map((pet) => {
if(pet.id !== action.petId){return pet;}
const updated pet = {}
// Do something with the pet or call a deeper Reducer if required
return (updatedPet);
});
},
};
const PetReducer = function(state=[], action){
if (questionsActionMap[action.type]) {
return petActionMap[action.type](state, action);
} else {
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment