Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 39 additions & 90 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"devDependencies": {
"@cypress/react18": "^2.0.1",
"@mate-academy/scripts": "^1.8.5",
"@mate-academy/scripts": "^2.1.3",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
170 changes: 154 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,164 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useState, useEffect } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { USER_ID, getTodos, addTodo, deleteTodo, updateTodo } from './api/todos';
import { Todo } from './types/Todo';
import { FilterStatus } from './types/FilterStatus';
import { Header } from './Header/Header';
import { TodoList } from './TodoList/TodoList';
import { Footer } from './Footer/Footer';
// eslint-disable-next-line max-len
import { ErrorNotification } from './ErrorNotification/ErrorNotification';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [filter, setFilter] = useState(FilterStatus.All);
const [newTodoTitle, setNewTodoTitle] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

const filteredTodos = todos.filter(todo => {
if (filter === FilterStatus.Active) {
return !todo.completed;
}

if (filter === FilterStatus.Completed) {
return todo.completed;
}

return true;
});

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => setErrorMessage('Unable to load todos'));
}, []);

useEffect(() => {
if (errorMessage) {
const timer = setTimeout(() => setErrorMessage(''), 3000);

return () => clearTimeout(timer);
}

return undefined;
}, [errorMessage]);

const handleAddTodo = async (event: React.FormEvent) => {
event.preventDefault();

const trimmedTitle = newTodoTitle.trim();

if (!trimmedTitle) {
setErrorMessage('Title should not be empty');

return;
}

setTempTodo({
id: 0,
userId: USER_ID,
title: trimmedTitle,
completed: false,
});

try {
const createdTodo = await addTodo({
title: trimmedTitle,
completed: false,
userId: USER_ID,
});

setTodos(current => [...current, createdTodo]);
setNewTodoTitle('');
} catch {
setErrorMessage('Unable to add a todo');
} finally {
setTempTodo(null);
}
};

const handleToggleTodo = async (todo: Todo) => {
setLoadingTodoIds(current => [...current, todo.id]);

try {
const updatedTodo = await updateTodo({
...todo,
completed: !todo.completed,
});

setTodos(current =>
current.map(item => (item.id === updatedTodo.id ?
updatedTodo : item)),
);
} catch {
setErrorMessage('Unable to update a todo');
} finally {
setLoadingTodoIds(current => current.filter(id => id !==
todo.id));
}
};

const handleDeleteTodo = async (todoId: number) => {
setLoadingTodoIds(current => [...current, todoId]);

try {
await deleteTodo(todoId);
setTodos(current => current.filter(todo => todo.id !== todoId));
} catch {
setErrorMessage('Unable to delete a todo');
} finally {
setLoadingTodoIds(current => current.filter(id => id !== todoId));
}
};

const handleClearCompleted = () => {
todos
.filter(todo => todo.completed)
.forEach(todo => handleDeleteTodo(todo.id));
};
Comment on lines +116 to +120
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should use Promise.all() here


if (!USER_ID) {
return <UserWarning />;
}

return (
<section className="section container">
<p className="title is-4">
Copy all you need from the prev task:
<br />
<a href="https://github.com/mate-academy/react_todo-app-add-and-delete#react-todo-app-add-and-delete">
React Todo App - Add and Delete
</a>
</p>

<p className="subtitle">Styles are already copied</p>
</section>
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<Header
todos={todos}
newTodoTitle={newTodoTitle}
onTitleChange={setNewTodoTitle}
onSubmit={handleAddTodo}
isAdding={tempTodo !== null}
/>

{(todos.length > 0 || tempTodo) && (
<>
<TodoList
todos={filteredTodos}
tempTodo={tempTodo}
loadingTodoIds={loadingTodoIds}
onDelete={handleDeleteTodo}
onToggle={handleToggleTodo}
/>
<Footer
todos={todos}
filter={filter}
onFilterChange={setFilter}
onClearCompleted={handleClearCompleted}
/>
</>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
onClose={() => setErrorMessage('')}
/>
</div>
);
};
29 changes: 29 additions & 0 deletions src/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React from 'react';
import cn from 'classnames';

type Props = {
errorMessage: string;
onClose: () => void;
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
onClose,
}) => {
return (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !errorMessage,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>
{errorMessage}
</div>
);
};
72 changes: 72 additions & 0 deletions src/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import React from 'react';
import cn from 'classnames';
import { FilterStatus } from '../types/FilterStatus';

type Props = {
todos: { completed: boolean }[];
filter: FilterStatus;
onFilterChange: (filter: FilterStatus) => void;
onClearCompleted: () => void;
};

export const Footer: React.FC<Props> = ({
todos,
filter,
onFilterChange,
onClearCompleted,
}) => {
const hasCompleted = todos.some(todo => todo.completed);

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{todos.filter(todo => !todo.completed).length} items left
</span>

<nav className="filter" data-cy="Filter">
<a
href="#/"
className={cn('filter__link', {
selected: filter === FilterStatus.All,
})}
data-cy="FilterLinkAll"
onClick={() => onFilterChange(FilterStatus.All)}
>
All
</a>

<a
href="#/active"
className={cn('filter__link', {
selected: filter === FilterStatus.Active,
})}
data-cy="FilterLinkActive"
onClick={() => onFilterChange(FilterStatus.Active)}
>
Active
</a>

<a
href="#/completed"
className={cn('filter__link', {
selected: filter === FilterStatus.Completed,
})}
data-cy="FilterLinkCompleted"
onClick={() => onFilterChange(FilterStatus.Completed)}
>
Completed
</a>
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompleted}
disabled={!hasCompleted}
>
Clear completed
</button>
</footer>
);
};
52 changes: 52 additions & 0 deletions src/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { useEffect, useRef } from 'react';
import cn from 'classnames';
import { Todo } from '../types/Todo';

type Props = {
todos: Todo[];
newTodoTitle: string;
onTitleChange: (title: string) => void;
onSubmit: (e: React.FormEvent) => void;
isAdding: boolean;
};

export const Header: React.FC<Props> = ({
todos,
newTodoTitle,
onTitleChange,
onSubmit,
isAdding,
}) => {
const inputRef = useRef<HTMLInputElement>(null);
const allCompleted = todos.length > 0 && todos.every(todo => todo.completed);

useEffect(() => {
inputRef.current?.focus();
}, [isAdding, todos.length]);

return (
<header className="todoapp__header">
{todos.length > 0 && (
<button
type="button"
className={cn('todoapp__toggle-all', { active: allCompleted })}
data-cy="ToggleAllButton"
/>
)}

<form onSubmit={onSubmit}>
<input
ref={inputRef}
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={newTodoTitle}
onChange={e => onTitleChange(e.target.value)}
disabled={isAdding}
/>
</form>
</header>
);
};
Loading
Loading