Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active March 20, 2017 22:44
Show Gist options
  • Save StevenJL/2fdb3dd63274bef32d45 to your computer and use it in GitHub Desktop.
Save StevenJL/2fdb3dd63274bef32d45 to your computer and use it in GitHub Desktop.
// an initial state
// `const` means the variable cannot be reassigned, it does not
// `const` DOES NOT mean the value it points to is immutable
const initialState = {
visbilityFilter: "SHOW ALL",
todos: []
}
// The naming convention is we call the reducer the same name as whatever it is updating.
// In this case, it is a reducer that updates the todo-app, so we just call it `todoApp`.
// Note the first time this reducer is called, the state is undefined, so
// we set a default value. This setting of a default value is an ES 6 feature.
function todoApp(state=initialState, action){
switch(action.type){
case "SET_VISIBILITY_FILTER":
// Object.assign is from ES6, it let's us not alter the state, instead we make a copy of it with the updated values
// object immutability is the philosophy of Redux
return Object.assign({}, state, {
visibilityFilter: action.filter
})
case "ADD_TODO":
return Object.assign({}, state, {
todos: [
// These three dots is called a `spread`, a new feature of ES6:
// http://odetocode.com/blogs/scott/archive/2014/09/02/features-of-es6-part-5-the-spread.aspx
...state.todos,
{
text: action.text,
completed: false
}
]
})
case "COMPLETE_TODO":
return Object.assign({}, state, {
todos: [
...state.todos.slice(0, action.index),
Object.assign({}, state.todos[action.index], {
completed: true
}),
...state.todos.slice(action.index + 1)
]
})
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment