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://anastasiia-levochkina.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
254 changes: 239 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,250 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
getTodos,
createTodo,
deleteTodo,
updateTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { FilterType } from './types/FilterType';
import { TodoHeader } from './components/TodoHeader';
import { TodoList } from './components/TodoList';
import { TodoFooter } from './components/TodoFooter';
import { ErrorNotification } from './components/ErrorNotification';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [newTitle, setNewTitle] = useState('');
const [loadingIds, setLoadingIds] = useState<number[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [filter, setFilter] = useState<FilterType>(FilterType.All);
const [editingId, setEditingId] = useState<number | null>(null);
const [editingTitle, setEditingTitle] = useState('');

const inputRef = useRef<HTMLInputElement>(null);

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

return () => clearTimeout(timer);
}

return undefined;
}, [errorMessage]);

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

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

const title = newTitle.trim();

if (!title) {
setErrorMessage('Title should not be empty');
setTimeout(() => {
inputRef.current?.focus();
}, 0);

return;
}

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

setTempTodo(temp);

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

setTodos(prev => [...prev, created]);
setNewTitle('');
} catch {
setErrorMessage('Unable to add a todo');
} finally {
setTempTodo(null);
setTimeout(() => {
inputRef.current?.focus();
}, 0);
}
};

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

try {
await deleteTodo(id);
setTodos(prev => prev.filter(todo => todo.id !== id));
} catch {
setErrorMessage('Unable to delete a todo');
} finally {
setLoadingIds(prev => prev.filter(item => item !== id));
inputRef.current?.focus();
}
};

const handleToggle = 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 {
setErrorMessage('Unable to update a todo');
} finally {
setLoadingIds(prev => prev.filter(id => id !== todo.id));
}
};

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

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

await Promise.all(toUpdate.map(todo => handleToggle(todo)));
};

const handleEditStart = (todo: Todo) => {
setEditingId(todo.id);
setEditingTitle(todo.title);
};

const handleEditSave = async (todo: Todo) => {
const trimmed = editingTitle.trim();

if (trimmed === todo.title) {
setEditingId(null);

return;
}

if (!trimmed) {
setLoadingIds(prev => [...prev, todo.id]);

try {
await deleteTodo(todo.id);

setTodos(prev => prev.filter(t => t.id !== todo.id));
setEditingId(null);
} catch {
setErrorMessage('Unable to delete a todo');

return;
} finally {
setLoadingIds(prev => prev.filter(id => id !== 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)));

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

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

const activeCount = todos.filter(todo => !todo.completed).length;
const hasCompleted = todos.some(todo => todo.completed);

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

const handleClearCompleted = () => {
Promise.all(
todos.filter(todo => todo.completed).map(todo => handleDelete(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">
<TodoHeader
todos={todos}
newTitle={newTitle}
tempTodo={tempTodo}
inputRef={inputRef}
onToggleAll={handleToggleAll}
onSubmit={handleSubmit}
onNewTitleChange={setNewTitle}
/>

{(todos.length > 0 || tempTodo) && (
<TodoList
todos={visibleTodos}
tempTodo={tempTodo}
loadingIds={loadingIds}
editingId={editingId}
editingTitle={editingTitle}
onToggle={handleToggle}
onDelete={handleDelete}
onEditStart={handleEditStart}
onEditSave={handleEditSave}
onEditTitleChange={setEditingTitle}
onEditCancel={() => setEditingId(null)}
/>
)}

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

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

export const USER_ID = 3953; // твой id

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

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

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

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

interface ErrorNotificationProps {
message: string;
onClose: () => void;
}

export const ErrorNotification: React.FC<ErrorNotificationProps> = ({
message,
onClose,
}) => {
return (
<div
data-cy="ErrorNotification"
className={classNames('notification is-danger is-light', {
hidden: !message,
})}
>
<button
data-cy="HideErrorButton"
className="delete"
onClick={onClose}
/>
{message}
</div>
);
};
Loading