> Redux is a predictable state container for JavaScript apps.
The core idea is the single source of truth
Action is a JavaScript object.
{
type: "ADD_TODO",
payload: {
content: "Todo Content blah blah",
creator: "creator who who"
}
}
Pure function that returns an “action”
function addTodo(todo) {
return {
type: "ADD_TODO",
payload: todo,
};
}
Reducer is a JavaScript function that takes (previous state, action) and returns a new state.
- it has to be a pure function
function TodoReducer(previousState = [], action) {
switch (action.type) {
case "ADD_TODO":
return [...previousState, action.paylod];
case "DELETE_TODO":
// ...
return;
case "UPDATE_TODO":
// ...
return;
default:
return previousState;
}
}
The store is the object that brings everything together.
- Holds application state
- Allows access to state via
getState()
- Allows state to be updated via
dispatch(action)
- Registers listeners via
subscribe(listener)
- Handles unregistering of listeners via the function returned by
subscribe(listener)
It’s responsible for a lot of things.
However, we almost never directly touch the store. Instead, we use other library such as ng-redux
and react-redux
for React.
For now, think store
as a giant single data source like database.
store
is a JavaScript object that maps a sub-state to a corresponding reducer.
import { combineReducers } from "redux";
import middlewares from "./some-random-middlewares";
const reducers = combinReducers({
todo: TodoReducer,
notes: NoteReducer,
menus: MenuReducer,
});
const store = createStore(reducers, middlewares);
// dispatch an action
store.dispatch({
type: "ADD_TODO",
payload: someTodo
});
// get state
store.getState()
// {
// todo: [ someTodo, ... ],
// notes: ...,
// menus: ...
// }
However, eventually there will be the only one store in the application and it takes a single (combined) reducer. There could be many nested reducers.
yarn
yarn start
tree src
src ├── app │ ├── root.component.html │ ├── root.component.js │ ├── root.config.js │ ├── root.module.js │ └── todo │ ├── redux │ │ ├── action │ │ │ ├── index.js │ │ │ └── types.js │ │ └── reducer │ │ └── index.js │ ├── todo-form │ │ ├── todo-form.component.html │ │ ├── todo-form.component.js │ │ └── todo-form.controller.js │ ├── todo-item │ │ ├── todo-item.component.html │ │ └── todo-item.component.js │ ├── todo-list │ │ ├── todo-list.component.html │ │ ├── todo-list.component.js │ │ └── todo-list.controller.js │ └── todo.module.js └── index.js 8 directories, 17 files