Learn more
// Action type.
const ADD_TODO = 'ADD_TODO';
// Action creator.
function addTodo(todo) {
return { type: ADD_TODO, todo };
}
// Reducer state.
initialState = {
todos: ['Buy coffee'],
};
// Reducer.
function todoReducer(state = initialState, action) {
switch (action.type) {
// Handle each possible type of action.
case ADD_TODO:
return {
...state,
todos: todos.concat(action.todo),
},
default:
return state;
}
}
// Create a store from your reducer.
const todoStore = createStore(todoReducer);
// Invoke an action.
todoStore.dispatch(addTodo('Drink coffee'));
// Render a component.
const TodoSummary = (props) => {
const { todos } = props;
return (
<div>{todos.length}</div>
);
}
// Extract props for your component.
function mapStateToProps(todoStore, props) {
return {
todos: todoStore.todos,
};
}
// Connect your component to the store.
const TodoSummaryConnected = connect(mapStateToProps)(TodoSummary);
// Render your app.
const App = () => (
<Provider store={todoStore}>
<TodoSummaryConnected />
</Provider>
)
Learn more
initialState = {
todos: ['Buy coffee'],
};
// Create a reducer hook + dispatchers. Params are useRedux(storeName, initialState, reducers).
const [useTodoList, { addTodo }] = useRedux(
"todoList",
initialState,
{
addTodo: (todos, todo) => todos.concat(todo),
}
);
// Invoke an action.
addTodo('Drink coffee');
// Render a component.
const TodoSummary = () => {
const { todos } = useTodoList();
return (
<div>{todos.length}</div>
);
}
// Render your app.
const App = () => (
<Provider>
<TodoSummaryConnected />
</Provider>
)