Redux Training
by Sam Fereday
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
JavaScript
/// - ACTIONS
// We send them to the store using store.dispatch(). A type MUST be added, recommended as a string const, and then you can put whatever other properties you like after it.
// Actions are the only source of information, they're plain js objects and nothing more.
const ADD_TODO = 'ADD_TODO';
const TOGGLE_TODO = 'TOGGLE_TODO';
const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
// Other consts
const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
}
/// - ACTION CREATORS
// Actions creators create... well, actions. They're functions that create actions, so don't get them mixed up. Notice how portable this now is for testing, etc.
const addTodoAction = (text) => {
return {
type: ADD_TODO,
text
}
};
const toggleTodo = (index) => {
return {
type: TOGGLE_TODO,
index
}
};
const setVisibilityFilter = (filter) => {
return {
type: SET_VISIBILITY_FILTER,
filter
}
};
/// - USAGE
// Imagine an array of actions with their own indexes, make sure to keep the data as minimal as possible.
// So how would you dispatch that action? Here's one way:
const boundAddTodo = text => dispatch(addTodo(text));
const boundCompleteTodo = index => dispatch(completeTodo(index));
// Now you can call them whenenver you need to:
boundAddTodo('Some text for a todo');
boundCompleteTodo(23);
/// - REDUCERS
// Reducers specify how the applications state changes in response to the actions sent to the store. Remember, actions only describe the fact that something happened, but don't have any logic about how the state changes. Remember to try and keep data separate from the UI state.
// A reducer is a pure function that takes the previous state and an action, then return the next state:
// (previousState, action) => newState
/* Never do these in a reducer, it must be pure:
- Mutate its arguments;
- Perform side effects like API calls and routing transitions;
- Call non-pure functions,...