Created
August 30, 2016 23:56
-
-
Save laytong/19b20dd02963d9b71ee5ef1ec87815d2 to your computer and use it in GitHub Desktop.
Nested reducer pattern for deeply nested state
This file contains hidden or 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
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