Skip to content

Instantly share code, notes, and snippets.

@luismartinezs
Created November 29, 2018 09:28
Show Gist options
  • Save luismartinezs/77b4a3666fca6e001cbf804a47db3722 to your computer and use it in GitHub Desktop.
Save luismartinezs/77b4a3666fca6e001cbf804a47db3722 to your computer and use it in GitHub Desktop.
Redux basic pattern #redux
// state:
const state = {
todos: [{
text: 'Eat food',
completed: true
}, {
text: 'Exercise',
completed: false
}],
visibilityFilter: 'SHOW_COMPLETED'
};
// Actions:
const ADD_TODO = { type: 'ADD_TODO', text: 'Go to swimming pool' };
const TOGGLE_TODO = { type: 'TOGGLE_TODO', index: 1 };
const SET_VISIBILITY_FILTER = { type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' };
// "Partial" reducers:
// Each reducer manages a part of the state
function visibilityFilter(state = 'SHOW_ALL', action) {
if (action.type === 'SET_VISIBILITY_FILTER') {
return action.filter
} else {
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([{ text: action.text, completed: false }])
case 'TOGGLE_TODO':
return state.map(
(todo, index) =>
action.index === index
? { text: todo.text, completed: !todo.completed }
: todo
)
default:
return state
}
}
// Global reducer:
function todoApp(state = {}, action) {
return {
todos: todos(state.todos, action),
visibilityFilter: visibilityFilter(state.visibilityFilter, action)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment