Skip to content

Commit

Permalink
Add helper function for visible todos and replace filter anonymous fu…
Browse files Browse the repository at this point in the history
…nctions
  • Loading branch information
rialleons committed Oct 6, 2023
1 parent afe1cef commit 46dd5fc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
36 changes: 21 additions & 15 deletions src/components/Main/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,30 @@ export const Main: React.FC = () => {

const [isChecked, setIsChecked] = useState(false);

let filteredTodos: Todo[] = [];
const getVisibleTodos = (allTodos: Todo[], filter: Status) => {
let shownTodos: Todo[] = [];

switch (currentFilter) {
case Status.All:
filteredTodos = [...todos];
break;
switch (filter) {
case Status.All:
shownTodos = [...allTodos];
break;

case Status.Active:
filteredTodos = todos.filter(todo => !todo.completed);
break;
case Status.Active:
shownTodos = allTodos.filter(todo => !todo.completed);
break;

case Status.Completed:
filteredTodos = todos.filter(todo => todo.completed);
break;
case Status.Completed:
shownTodos = allTodos.filter(todo => todo.completed);
break;

default:
throw new Error('Unknown filter!');
}
default:
throw new Error('Unknown filter!');
}

return shownTodos;
};

const visibleTodos = getVisibleTodos(todos, currentFilter);

const handleToggleAllClick = () => {
setIsChecked(!isChecked);
Expand All @@ -50,7 +56,7 @@ export const Main: React.FC = () => {
/>
<label htmlFor="toggle-all">Mark all as complete</label>

<TodoList items={filteredTodos} />
<TodoList items={visibleTodos} />
</section>
);
};
10 changes: 7 additions & 3 deletions src/components/TodosFilter/TodosFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import { TodosContext } from '../TodosContext';
export const TodosFilter: React.FC = () => {
const { currentFilter, setCurrentFilter } = useContext(TodosContext);

const onFilterSelect = (status: Status) => () => {
setCurrentFilter(status);
};

return (
<ul className="filters" data-cy="todosFilter">
<li>
Expand All @@ -16,7 +20,7 @@ export const TodosFilter: React.FC = () => {
className={classNames({
selected: currentFilter === Status.All,
})}
onClick={() => setCurrentFilter(Status.All)}
onClick={onFilterSelect(Status.All)}
>
{Status.All}
</a>
Expand All @@ -28,7 +32,7 @@ export const TodosFilter: React.FC = () => {
className={classNames({
selected: currentFilter === Status.Active,
})}
onClick={() => setCurrentFilter(Status.Active)}
onClick={onFilterSelect(Status.Active)}
>
{Status.Active}
</a>
Expand All @@ -40,7 +44,7 @@ export const TodosFilter: React.FC = () => {
className={classNames({
selected: currentFilter === Status.Completed,
})}
onClick={() => setCurrentFilter(Status.Completed)}
onClick={onFilterSelect(Status.Completed)}
>
{Status.Completed}
</a>
Expand Down

0 comments on commit 46dd5fc

Please sign in to comment.