Implementing Reducers
Reducers are functions that specify how the state should be updated when an action is dispatched. In Redux, reducers have a very specific signature. They accept two arguments: the current state and the action being dispatched.
Here's an example of a basic reducer that handles the state changes for a TODO application:
1const initialState = {
2 todos: [],
3 filter: 'all'
4};
5
6const todoReducer = (state = initialState, action) => {
7 switch (action.type) {
8 case 'ADD_TODO': {
9 const { id, text } = action.payload;
10 const newTodo = { id, text, completed: false };
11 return {
12 ...state,
13 todos: [...state.todos, newTodo]
14 };
15 }
16 case 'TOGGLE_TODO': {
17 const { id } = action.payload;
18 const updatedTodos = state.todos.map(todo =>
19 todo.id === id ? { ...todo, completed: !todo.completed } : todo
20 );
21 return {
22 ...state,
23 todos: updatedTodos
24 };
25 }
26 case 'SET_FILTER': {
27 const { filter } = action.payload;
28 return {
29 ...state,
30 filter
31 };
32 }
33 default:
34 return state;
35 }
36};
In the example above, the todoReducer
function handles the state updates for a TODO application. It accepts the current state and the action as arguments. Depending on the action type, it performs the necessary state changes and returns a new state object.
Reducers are pure functions, which means they should always return a new state object and not modify the existing state. This ensures that the state changes are predictable and easier to debug.
Feel free to test the above reducer by executing the code snippet in your JavaScript environment.
xxxxxxxxxx
console.log(todoReducer(initialState, { type: 'ADD_TODO', payload: { id: 1, text: 'Buy groceries' } }));
// Replace this code with your implementation of a Redux reducer
const initialState = {
todos: [],
filter: 'all'
};
const todoReducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD_TODO': {
const { id, text } = action.payload;
const newTodo = { id, text, completed: false };
return {
state,
todos: [state.todos, newTodo]
};
}
case 'TOGGLE_TODO': {
const { id } = action.payload;
const updatedTodos = state.todos.map(todo =>
todo.id === id ? { todo, completed: !todo.completed } : todo
);
return {
state,
todos: updatedTodos
};
}
case 'SET_FILTER': {
const { filter } = action.payload;