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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ Implement the ability to edit a todo title on double click:

- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://DmytroYakovchuk.github.io/react_todo-app-with-api/) and add it to the PR description.
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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
277 changes: 260 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,269 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { TodoList } from './components/TodoList';
import { Filter } from './api/types/Filters';
import { TempTodo } from './components/TempTodo';
import { updateTodo } from './api/todos';
import React, { useEffect, useState, useRef, useCallback } from 'react';

const USER_ID = 0;
import { Todo } from './api/types/Todo';
import { addTodo, deleteTodo, getTodos, USER_ID } from './api/todos';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [error, setError] = useState<string | null>(null);
const [filter, setFilter] = useState(Filter.All);
const [newTitle, setNewTitle] = useState('');
const [isAdding, setIsAdding] = useState(false);

const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [deletingIds, setDeletingIds] = useState<number[]>([]);
const [loadingIds, setLoadingIds] = useState<number[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
const [editingTodoId, setEditingTodoId] = useState<number | null>(null);

const showError = (message: string) => {
setError(message);

setTimeout(() => {
setError(null);
}, 3000);
};

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

const trimmedTitle = newTitle.trim();

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

return;
}

setIsAdding(true);

const newTodo = {
userId: USER_ID,
title: trimmedTitle,
completed: false,
};

setTempTodo({
id: 0,
...newTodo,
});

const promise = addTodo(newTodo);

try {
const createdTodo = await promise;

setTodos(prev => [...prev, createdTodo]);
setNewTitle('');
} catch {
showError('Unable to add a todo');
} finally {
setTempTodo(null);
setIsAdding(false);
inputRef.current?.focus();
}
};

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

setTodos(data);
} catch {
showError('Unable to load todos');
}
}, []);

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

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

const handleToggle = async (id: number) => {
const todo = todos.find(item => item.id === id);

if (!todo) {
return;
}

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

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

setTodos(prev => prev.map(item => (item.id === id ? updatedTodo : item)));
} catch {
showError('Unable to update a todo');
} finally {
setLoadingIds(prev => prev.filter(itemId => itemId !== id));
}
};

const handleToggleAll = async () => {
const allCompleted =
todos.length > 0 && todos.every(todo => todo.completed);

const targetCompleted = !allCompleted;

const todosToUpdate = todos.filter(
todo => todo.completed !== targetCompleted,
);

const idsToUpdate = todosToUpdate.map(todo => todo.id);

setLoadingIds(prev => [...prev, ...idsToUpdate]);

try {
const updatedTodos = await Promise.all(
todosToUpdate.map(todo =>
updateTodo(todo.id, {
completed: targetCompleted,
}),
),
);

setTodos(current =>
current.map(todo => {
const updated = updatedTodos.find(item => item.id === todo.id);

return updated || todo;
}),
);
} catch {
showError('Unable to update a todo');
} finally {
setLoadingIds(prev => prev.filter(id => !idsToUpdate.includes(id)));
}
};

const handleRename = async (id: number, title: string) => {
setLoadingIds(prev => [...prev, id]);

try {
const updatedTodo = await updateTodo(id, { title });

setTodos(prev => prev.map(todo => (todo.id === id ? updatedTodo : todo)));

setEditingTodoId(null);
} catch {
showError('Unable to update a todo');
} finally {
setLoadingIds(prev => prev.filter(item => item !== id));
}
};

const handleDelete = async (id: number) => {
try {
setDeletingIds(prev => [...prev, id]);

await deleteTodo(id);

setTodos(prev => prev.filter(todo => todo.id !== id));
} catch {
showError('Unable to delete a todo');
} finally {
setDeletingIds(prev => prev.filter(item => item !== id));
inputRef.current?.focus();
}
};

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

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

const successIds = completed
.filter((_, i) => results[i].status === 'fulfilled')
.map(todo => todo.id);

const hasError = results.some(r => r.status === 'rejected');

setTodos(prev => prev.filter(todo => !successIds.includes(todo.id)));

if (hasError) {
showError('Unable to delete a todo');
}

inputRef.current?.focus();
};

const visibleTodos = todos.filter(todo => {
switch (filter) {
case Filter.Active:
return !todo.completed;

case Filter.Completed:
return todo.completed;

case Filter.All:
default:
return true;
}
});

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={handleSubmit}
isAdding={isAdding}
inputRef={inputRef}
hasTodos={todos.length > 0}
allCompleted={todos.every(t => t.completed)}
onToggleAll={handleToggleAll}
/>

{(todos.length > 0 || tempTodo) && (
<section className="todoapp__main" data-cy="TodoList">
<TodoList
todos={visibleTodos}
deletingIds={deletingIds}
loadingIds={loadingIds}
onDelete={handleDelete}
onToggle={handleToggle}
onRename={handleRename}
onStartEditing={setEditingTodoId}
onCancelEditing={() => setEditingTodoId(null)}
editingTodoId={editingTodoId}
/>

{tempTodo && <TempTodo todo={tempTodo} />}
</section>
)}

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

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

export const USER_ID = 1;

const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export const getTodos = async () => {
await wait(150);

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

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

export const deleteTodo = async (id: number) => {
await wait(150);

return client.delete(`/todos/${id}`);
};

export const updateTodo = async (id: number, data: Partial<Todo>) => {
await wait(150);

return client.patch<Todo>(`/todos/${id}`, data);
};
// Add more methods here
5 changes: 5 additions & 0 deletions src/api/types/Filters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export enum Filter {
All = 'all',
Active = 'active',
Completed = 'completed',
}
6 changes: 6 additions & 0 deletions src/api/types/Todo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface Todo {
id: number;
userId: number;
title: string;
completed: boolean;
}
Loading
Loading