Other improvements
Let's implement some other improvements to our todo list application:
- Add a checkbox to mark a todo item as completed
- Add a filter to show only the completed items, only the uncompleted items, or all items
- Add a button to remove all completed items
- Disable the Remove All button when there are no items to remove
- Disable the Remove Completed button when there are no completed items
Completing and filtering a todo item
The TodoItem class already has a boolean flag called completed
that indicates if the todo item is completed or not.
We will:
-
Create the
Filter
enum:export enum Filter {
showAll = 'Showing ALL',
showCompleted = 'Showing COMPLETED',
showActive = 'Showing ACTIVE',
} -
Add the filter state to the
State
class:export class State {
todoList: TodoList;
readonly filter: Filter;
constructor({todoList, filter}: { todoList: TodoList, filter: Filter }) {
this.todoList = todoList;
this.filter = filter;
}
withTodoList(todoList: TodoList): State {
return new State({ todoList: todoList, filter: this.filter });
}
withFilter(filter: Filter): State {
return new State({todoList: this.todoList, filter: filter});
}
static initialState: State = new State({
todoList: TodoList.empty,
filter: Filter.showAll
});
} -
Add a checkbox to the
TodoItemComponent
that allows the user to mark the todo item as completed. The checkbox dispatches theToggleTodoAction
action. -
Modify the
TodoItemComponent
so that it only shows the item if it matches the filter. -
Add the
RemoveCompletedButton
component that dispatches theRemoveCompletedTodosAction
. The button is disabled when there are no completed items. -
Modify the
RemoveAllButton
component so that it is disabled when there are no items to remove. -
Add the
FilterButton
component that dispatches theNextFilterAction
action. This button text is based on the current filter: "Showing all", "Showing completed", or "Showing active".
Try it yourself
Click the "Add Random Todo" a few times, to add some items to the list. Then, mark some of them as completed, and click the "Showing all" button to see how the filter works.
Read the code below and try to understand how it works.