DEV Community

Cover image for Building Todo App Actions and Reducers with Redux - Part 2
Aneeqa Khan
Aneeqa Khan

Posted on

Building Todo App Actions and Reducers with Redux - Part 2

In my last blog, I wrote about actions and reducers to AddTodo and ToggleTodo. Today I'll write about Visibility Filters. i.e., to show All, Active, and Completed todos.

Check Part 1 here

Scenarios

Let's dive into it. I want to show todos upon these three filters

  • Show All todos
  • Active todos
  • Completed todos

Action

First, define the action like this

const setVisibiltyFilter = filter => {
  return {
    type: "SET_VISIBILTY_FILTER",
    filter: filter
  };
};
Enter fullscreen mode Exit fullscreen mode

It'll take any of the above-mentioned filter types and pass it to the reducer to set visibility state.

Reducer

Now its time to write TodoReducer

const initialState = {
  todos: [],
  visibilityFilter: "SHOW_ALL"
};

const TodoReducer = (state = initialState, action) => {
  switch (action.type) {
    case "SET_VISIBILTY_FILTER":
      return action.filter;
    default:
      return state;
  }
};
Enter fullscreen mode Exit fullscreen mode

It will set filter value passed it in action to visibilityFilter and its default value is SHOW_ALL.

Now to show selected filter todos on screen, I defined these three filters in getVisibleTodos reducer, its getting todos state in props from component and returning filtered todos.

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case "SHOW_ALL":
      return todos;
    case "SHOW_COMPLETED":
      return todos.filter(t => t.completed);
    case "SHOW_ACTIVE":
      return todos.filter(t => !t.completed);
  }
};
Enter fullscreen mode Exit fullscreen mode

I map the getVisibleTodos to the component props like this and its returning todos list to component.

const mapStateToTodoListProps = state => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  };
};
Enter fullscreen mode Exit fullscreen mode

Execution

You can check and run the app below.

Top comments (2)

Collapse
 
abolfazlhasanzadeh profile image
Abolfazl Hasanzadeh

nice :)

Collapse
 
bushra134 profile image
Bushra

can you help me please