Building Todo App Actions and Reducers with Redux — Part 2

Aneeqa Khan
2 min readJul 7, 2020

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
};
};

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;
}
};

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);
}
};

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

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

Execution

You can check and run the app below.

--

--

Aneeqa Khan

I’m a frontend web and mobile developer specialized in web/mobile designs and frontend frameworks. I usually work with React, React Native, Next and TypeScript.