Skip to content

Instantly share code, notes, and snippets.

@piq9117
Last active August 25, 2016 07:31
Show Gist options
  • Save piq9117/8dbd24ab956c5366dc34b0a007a9727a to your computer and use it in GitHub Desktop.
Save piq9117/8dbd24ab956c5366dc34b0a007a9727a to your computer and use it in GitHub Desktop.
const person = {
name: 'ken',
favoriteFood: []
}
/*
It's the same reducer function from above, I just extracted the operation for
'ADD_FOOD', turned into a function and named it addFood.
*/
function addFood (state, action) {
return Object.assign({}, state, {
favoriteFood: state.favoriteFood.concat(action.data.food)
})
}
/*
state = person, means that the person object
is the default value for state. It will fall back to that value
if I don't provide any value to it
*/
function reducer (state = person, action) {
switch (action.type) {
case 'ADD_FOOD':
return addFood(state, action)
}
}
/*
I've provided the person object as the state input,
and an object for the action.
*/
const result = reducer(person, {
type: 'ADD_FOOD',
data: {
food: 'apple'
}
})
/*
The output:
const person = {
name: 'ken',
favoriteFood: ['apple']
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment