Mark As Completed Discussion

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:

JAVASCRIPT
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.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment