Building Todo App Actions and Reducers with Redux - Part 1

Aneeqa Khan - Jul 1 '20 - - Dev Community

Here this blog is about actions and reducers one might need to create a simple React Todo App.

In this blog, I'll cover only how to add todo item and toggle its status from incomplete to complete and vice versa.

Scenarios

So for this, we need actions and reducers of two cases.

  1. Add Todo Item.
  2. Toggle Todo Item.

Actions

First I created a global variable to make ids of todos.

let nextTodoId = 0;
Enter fullscreen mode Exit fullscreen mode

Next, I wrote my add todo item action creator like this

const addTodo = text => {
  return {
    type: "ADD_TODO",
    text,
    id: nextTodoId++
  };
};
Enter fullscreen mode Exit fullscreen mode

It will take text written in textbox and pass it to reducer with an increment of nextTodoId.

Now toggle action will look like this

const toggleTodo = id => {
  return {
    type: "TOGGLE_TODO",
    id
  };
};
Enter fullscreen mode Exit fullscreen mode

It will take the id of clicked todo item and pass it to the reducer to toggle its state.

Reducer

Now its time to write TodoReducer

const initialState = {
  todos: [],
};
const TodoReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            id: action.id,
            text: action.text,
            completed: false,
          },
        ],
      };
    case 'TOGGLE_TODO':
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.id
            ? {
                ...state,
                completed: !state.completed,
              }
            : todo,
        ),
      };
    default:
      return state;
  }
};
Enter fullscreen mode Exit fullscreen mode

In ADD_TODO case, I am adding a new todo object into todos array and keeping its "completed" property as false by default and setting id and text passed by the action.

In TOGGLE_TODO case, I am finding the clicked todo item through .map and toggling its completed state.

Execution

That's it. I'll write the second part about Visibility Filter in the next blog. Thanks!

You can check and run the app below.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .