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
Building Todo App Actions and Reducers with Redux - Part 1
Aneeqa Khan ・ Jul 1 '20
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 component.
const mapStateToTodoListProps = state => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
};
};
Execution
You can check and run the app below.