Skip to content
Open

Develop #2120

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

const USER_ID = 0;
import {
getTodos,
createTodo,
deleteTodo,
USER_ID,
updateTodo,
} from './api/todos';
import { NewTodoForm } from './components/NewTodoForm';
import { Todo } from './types/Todo';
import { TodoList } from './components/TodoList';
import { Filter, FILTERS } from './types/Filters';
import { ErrorNotification } from './components/ErrorNotification';
import { FilterComponent } from './components/FilterComponent';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingIds, setLoadingIds] = useState<number[]>([]);
const [filter, setFilter] = useState<Filter>('all');
const [error, setError] = useState<string | null>(null);

const todoFieldRef = useRef<HTMLInputElement>(null);
const errorTimeoutRef = useRef<number | null>(null);

// Focus the input field
const focusField = useCallback(() => {
todoFieldRef.current?.focus();
}, []);

// Refocus input whenever temporary todo changes
useEffect(() => {
focusField();
}, [tempTodo, focusField]);

// Display error message and hide it automatically after 3 seconds
const showError = (message: string) => {
setError(message);

if (errorTimeoutRef.current) {
clearTimeout(errorTimeoutRef.current);
}

errorTimeoutRef.current = window.setTimeout(() => {
setError(null);
}, 3000);
};

// Load todos from API when the component mounts
useEffect(() => {
if (!USER_ID) {
return;
}

getTodos()
.then(setTodos)
.catch(() => showError('Unable to load todos'));

// Cleanup timeout on unmount
return () => {
if (errorTimeoutRef.current) {
clearTimeout(errorTimeoutRef.current);
}
};
}, []);

// Memoized calculations for derived todo lists
const { activeTodos, completedTodos, filteredTodos } = useMemo(() => {
const active = todos.filter(t => !t.completed);
const completed = todos.filter(t => t.completed);
let filtered = todos;

if (filter === FILTERS.active) {
filtered = active;
}

if (filter === FILTERS.completed) {
filtered = completed;
}

return {
activeTodos: active,
completedTodos: completed,
filteredTodos: filtered,
};
}, [todos, filter]);

// Derived UI states
const isAllCompleted = todos.length > 0 && todos.every(t => t.completed);
const hasTodos = todos.length > 0 || tempTodo;

// Add new todo
const handleAdd = async (title: string): Promise<boolean> => {
const trimmedTitle = title.trim();

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

return false;
}

// Optimistic UI: show temporary todo while request is in progress
setTempTodo({
id: 0,
userId: USER_ID,
title: trimmedTitle,
completed: false,
});

try {
const newTodo = await createTodo({ title: trimmedTitle });

setTodos(current => [...current, newTodo]);

return true;
} catch {
showError('Unable to add a todo');

return false;
} finally {
setTempTodo(null);
}
};

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

try {
await deleteTodo(id);
setTodos(prev => prev.filter(t => t.id !== id));
focusField();
} catch {
showError('Unable to delete a todo');
} finally {
setLoadingIds(prev => prev.filter(lid => lid !== id));
}
};

// toggle todo
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 {
showError('Unable to update a todo');
throw new Error('Update failed');
} finally {
setLoadingIds(prev => prev.filter(id => id !== todo.id));
}
};

const handleToggleAll = async () => {
const newStatus = !isAllCompleted;
const todosToUpdate = todos.filter(todo => todo.completed !== newStatus);

try {
await Promise.all(todosToUpdate.map(todo => handleToggle(todo)));
} catch {}
};

const handleRename = async (
todo: Todo,
newTitle: string,
): Promise<boolean> => {
const trimmed = newTitle.trim();

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

return true;
}

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

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)));

return true;
} catch {
showError('Unable to update a todo');

return false;
} finally {
setLoadingIds(prev => prev.filter(id => id !== todo.id));
}
};

// Remove all completed todos
const handleClearCompleted = async () => {
await Promise.allSettled(completedTodos.map(todo => handleDelete(todo.id)));
focusField();
};

// If USER_ID is missing, show warning instead of the app
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 className="todoapp__header">
{hasTodos && (
<button
type="button"
className={classNames('todoapp__toggle-all', {
active: isAllCompleted,
})}
data-cy="ToggleAllButton"
onClick={handleToggleAll}
/>
)}

<NewTodoForm
onAdd={handleAdd}
loading={!!tempTodo}
todoFieldRef={todoFieldRef}
/>
</header>

{hasTodos && (
<TodoList
todos={filteredTodos}
tempTodo={tempTodo}
loadingIds={loadingIds}
onDelete={handleDelete}
onToggle={handleToggle}
onRename={handleRename}
/>
)}

{/* Footer */}
{hasTodos && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{/*eslint-disable-next-line max-len*/}
{activeTodos.length} {activeTodos.length === 1 ? 'item' : 'items'}{' '}
left
</span>
<FilterComponent current={filter} onChange={setFilter} />
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={completedTodos.length === 0}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
)}
</div>
<ErrorNotification message={error} onClose={() => setError(null)} />
</div>
);
};
27 changes: 27 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 3981;

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

// Add more methods here
// Add new todo
export const createTodo = ({ title }: { title: string }) => {
return client.post<Todo>('/todos', {
title,
userId: USER_ID,
completed: false,
});
};

// Delete todo by id
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);
};
30 changes: 30 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import classNames from 'classnames';
import React from 'react';

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

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