Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
270 changes: 257 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,270 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';

import React, { useEffect, useMemo, useRef } from 'react';

import { UserWarning } from './UserWarning';
import { USER_ID } from './api/todos';
import { Todo } from './types/Todo';
import { getTodos, addTodo, deleteTodo, updateTodo } from './api/todos';

const USER_ID = 0;
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { Filter } from './types/Filter';

enum ErrorMessage {
Load = 'Unable to load todos',
Add = 'Unable to add a todo',
Delete = 'Unable to delete a todo',
EmptyTitle = 'Title should not be empty',
Update = 'Unable to update a todo',
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

it's better to move to separate file inside types` folder


export const App: React.FC = () => {
const [todos, setTodos] = React.useState<Todo[]>([]);
const [error, setError] = React.useState<string | null>(null);
const [newTitle, setNewTitle] = React.useState('');
const [tempTodo, setTempTodo] = React.useState<Todo | null>(null);
const [isAdding, setIsAdding] = React.useState(false);
const [deleteIds, setDeleteIds] = React.useState<number[]>([]);
const [filter, setFilter] = React.useState<Filter>(Filter.All);
const [loadingIds, setLoadingIds] = React.useState<number[]>([]);

const inputRef = useRef<HTMLInputElement>(null);

const loadTodos = async () => {
try {
const data = await getTodos();

setTodos(data);
} catch {
setTodos([]);
setError(ErrorMessage.Load);
}
};

useEffect(() => {
setTimeout(loadTodos, 0);
}, []);

useEffect(() => {
if (!error) {
return;
}

const timer = setTimeout(() => setError(null), 3000);

return () => clearTimeout(timer);
}, [error]);

useEffect(() => {
inputRef.current?.focus();
});

const activeCount = todos.filter(t => !t.completed).length;
const hasCompleted = todos.some(t => t.completed);
const allCompleted = todos.length > 0 && activeCount === 0;

const visibleTodos = useMemo(() => {
switch (filter) {
case Filter.Active:
return todos.filter(t => !t.completed);
case Filter.Completed:
return todos.filter(t => t.completed);
default:
return todos;
}
}, [todos, filter]);

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

const trimmed = newTitle.trim();

if (!trimmed) {
setError(ErrorMessage.EmptyTitle);

return;
}

const temp: Todo = {
id: 0,
title: trimmed,
completed: false,
userId: USER_ID,
};

setTempTodo(temp);
setIsAdding(true);

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

setTodos(prev => [...prev, created]);
setNewTitle('');
} catch {
setError(ErrorMessage.Add);
} finally {
setTempTodo(null);
setIsAdding(false);
}
};

const handleDeleteTodo = async (id: number) => {
setDeleteIds(prev => [...prev, id]);

try {
await deleteTodo(id);
setTodos(prev => prev.filter(t => t.id !== id));
} catch {
setError(ErrorMessage.Delete);
} finally {
setDeleteIds(prev => prev.filter(x => x !== id));
}
};

const handleClearCompleted = async () => {
const completed = todos.filter(t => t.completed);

const results = await Promise.allSettled(
completed.map(t => deleteTodo(t.id)),
);

const okIds: number[] = [];

results.forEach((r, i) => {
if (r.status === 'fulfilled') {
okIds.push(completed[i].id);
}
});

setTodos(prev => prev.filter(t => !okIds.includes(t.id)));

if (results.some(r => r.status === 'rejected')) {
setError(ErrorMessage.Delete);
}
};

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

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

setTodos(prev => prev.map(t => (t.id === todo.id ? updated : t)));
} catch {
setError(ErrorMessage.Update);
} finally {
setLoadingIds(prev => prev.filter(id => id !== todo.id));
}
};

const handleToggleAll = async () => {
const newStatus = !allCompleted;

const toUpdate = todos.filter(t => t.completed !== newStatus);

await Promise.all(
toUpdate.map(async todo => {
setLoadingIds(prev => [...prev, todo.id]);

try {
const updated = await updateTodo(todo.id, {
completed: newStatus,
});

setTodos(prev => prev.map(t => (t.id === todo.id ? updated : t)));
} catch {
setError(ErrorMessage.Update);
} finally {
setLoadingIds(prev => prev.filter(id => id !== todo.id));
}
}),
);
};

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

const handleRename = async (todo: Todo, update: string) => {
const trimmed = update.trim();

if (trimmed === todo.title) {
return;
}

if (!trimmed) {
await handleDeleteTodo(todo.id);

return;
}

setLoadingIds(prev => [...prev, todo.id]);

try {
const updated = await updateTodo(todo.id, {
title: trimmed,
});

setTodos(prev => prev.map(t => (t.id === todo.id ? updated : t)));
} catch {
setError(ErrorMessage.Update);

throw new Error('Unable to update');
} finally {
setLoadingIds(prev => prev.filter(id => id !== todo.id));
}
};

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
newTitle={newTitle}
setNewTitle={setNewTitle}
onSubmit={handleAddTodo}
isAdding={isAdding}
inputRef={inputRef}
allCompleted={allCompleted}
hasTodos={todos.length > 0}
onToggleAll={handleToggleAll}
/>

<TodoList
todos={visibleTodos}
deleteIds={deleteIds}
loadingIds={loadingIds}
onDelete={handleDeleteTodo}
onToggle={handleToggleTodo}
onRename={handleRename}
tempTodo={tempTodo}
isAdding={isAdding}
/>

{todos.length > 0 && (
<Footer
activeCount={activeCount}
filter={filter}
setFilter={setFilter}
hasCompleted={hasCompleted}
onClearCompleted={handleClearCompleted}
/>
)}
</div>

<ErrorNotification error={error} onClose={() => setError(null)} />
</div>
);
};
23 changes: 23 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 4139;

export const getTodos = () => {
return client.get<Todo[]>(`/todos?userId=${USER_ID}`);
};

export const addTodo = (todo: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', {
...todo,
userId: USER_ID,
});
};

export const deleteTodo = (id: number) => {
return client.delete(`/todos/${id}`);
};

export const updateTodo = (id: number, updates: Partial<Omit<Todo, 'id'>>) => {
return client.patch<Todo>(`/todos/${id}`, updates);
};
26 changes: 26 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react';

type Props = {
error: string | null;
onClose: () => void;
};

export const ErrorNotification: React.FC<Props> = ({ error, onClose }) => {
return (
<div
data-cy="ErrorNotification"
className={`notification is-danger is-light has-text-weight-normal ${
error ? '' : 'hidden'
}`}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>

{error}
</div>
);
};
59 changes: 59 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react';
import { Filter } from '../types/Filter';

type Props = {
activeCount: number;
filter: Filter;
setFilter: (value: Filter) => void;
hasCompleted: boolean;
onClearCompleted: () => void;
};

const filters = [
{ label: 'All', value: Filter.All, href: '#/' },
{ label: 'Active', value: Filter.Active, href: '#/active' },
{ label: 'Completed', value: Filter.Completed, href: '#/completed' },
];

export const Footer: React.FC<Props> = ({
activeCount,
filter,
setFilter,
hasCompleted,
onClearCompleted,
}) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeCount} items left
</span>

<nav className="filter" data-cy="Filter">
{filters.map(f => (
<a
key={f.value}
href={f.href}
className={`filter__link ${filter === f.value ? 'selected' : ''}`}
onClick={e => {
e.preventDefault();
setFilter(f.value);
}}
Comment on lines +37 to +40
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

move to separate fn

data-cy={`FilterLink${f.label}`}
>
{f.label}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!hasCompleted}
onClick={onClearCompleted}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading