Skip to content
Open

Develop #2270

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

const USER_ID = 0;
import * as clientMethods from './api/todos';
import type { Todo } from './types/Todo';
import { NewTodoForm } from './components/NewTodoForm';
import { TodoList } from './components/TodoList';
import { ErrorType } from './types/ErrorType';
import { FilterType } from './types/FilterType';
import { TodoItem } from './components/TodoItem';
import classNames from 'classnames';

export const App: React.FC = () => {
if (!USER_ID) {
const [todos, setTodos] = useState<Todo[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(ErrorType.None);
const [selectedFilterLink, setSelectedFilterLink] = useState(FilterType.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingIds, setLoadingIds] = useState<number[]>([]);

const inputFocusRef = useRef<HTMLInputElement>(null);

const completedTodos = todos.filter(todo => todo.completed);
const activeTodos = todos.filter(todo => !todo.completed);
const allTodosCompleted =
todos.length > 0 && todos.every(todo => todo.completed);

const filterLinks = [
{
label: 'All',
value: FilterType.All,
href: '#/',
dataCy: 'FilterLinkAll',
},
{
label: 'Active',
value: FilterType.Active,
href: '#/active',
dataCy: 'FilterLinkActive',
},
{
label: 'Completed',
value: FilterType.Completed,
href: '#/completed',
dataCy: 'FilterLinkCompleted',
},
];

const handleAddTodo = (newTodo: Todo): void => {
setTodos([...todos, newTodo]);
};

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

try {
await clientMethods.deleteTodo(deleteId);
setTodos(current => current.filter(todo => todo.id !== deleteId));
} catch (err) {
setError(ErrorType.Delete);
throw err;
} finally {
setLoadingIds(current => current.filter(id => id !== deleteId));
inputFocusRef.current?.focus();
}
};

const handleClearCompleted = () => {
Promise.all(completedTodos.map(todo => handleDelete(todo.id))).catch(
() => {},
);
};

const handleUpdate = async (id: number, todoData: Partial<Todo>) => {
setLoadingIds(current => [...current, id]);

try {
await clientMethods.updateTodo(id, todoData);
setTodos(current =>
current.map(todo => (todo.id === id ? { ...todo, ...todoData } : todo)),
);
} catch (err) {
setError(ErrorType.Update);
throw err;
} finally {
setLoadingIds(current => current.filter(item => item !== id));
}
};

const handleToggleAll = () => {
const targetStatus = !allTodosCompleted;
const todosToUpdate = todos.filter(todo => todo.completed !== targetStatus);

Promise.all(
todosToUpdate.map(todo =>
handleUpdate(todo.id, { completed: targetStatus }),
),
).catch(() => {});
};

useEffect(() => {
const loadTodos = async () => {
try {
const loadedTodos = await clientMethods.getTodos();

setTodos(loadedTodos);
} catch (err) {
setError(ErrorType.Load);
} finally {
setIsLoading(false);
}
};

loadTodos();
}, []);

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

const timer = setTimeout(() => setError(ErrorType.None), 3000);

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

let filteredTodos = todos;

switch (selectedFilterLink) {
case FilterType.Active:
filteredTodos = todos.filter(todo => !todo.completed);
break;
case FilterType.Completed:
filteredTodos = todos.filter(todo => todo.completed);
break;
default:
filteredTodos = todos;
break;
}

if (!clientMethods.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">
{todos.length > 0 && (
<button
type="button"
className={`todoapp__toggle-all ${allTodosCompleted ? 'active' : ''}`}
data-cy="ToggleAllButton"
onClick={handleToggleAll}
/>
)}

<NewTodoForm
onAdd={handleAddTodo}
onError={setError}
setTempTodo={setTempTodo}
inputFocusRef={inputFocusRef}
/>
</header>

<section className="todoapp__main" data-cy="TodoList">
{!isLoading && (
<>
<TodoList
todos={filteredTodos}
onDelete={handleDelete}
loadingIds={loadingIds}
handleUpdate={handleUpdate}
/>
{tempTodo && <TodoItem todo={tempTodo} isLoading />}
</>
)}
</section>

{todos.length > 0 && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${activeTodos.length} items left`}
</span>

<nav className="filter" data-cy="Filter">
{filterLinks.map(link => (
<a
key={link.value}
href={link.href}
className={`filter__link ${selectedFilterLink === link.value ? 'selected' : ''}`}
data-cy={link.dataCy}
onClick={() => setSelectedFilterLink(link.value)}
>
{link.label}
</a>
))}
</nav>

<button
type="button"
className={`todoapp__clear-completed
${completedTodos.length === 0 ? 'hidden' : ''}`}
data-cy="ClearCompletedButton"
onClick={handleClearCompleted}
disabled={completedTodos.length === 0}
>
Clear completed
</button>
</footer>
)}
</div>

<div
data-cy="ErrorNotification"
className={classNames(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{ hidden: !error },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(ErrorType.None)}
/>
{error}
</div>
</div>
);
};
22 changes: 22 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 4133;

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

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

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

export const updateTodo = (id: number, todoData: Partial<Todo> | undefined) => {
return client.patch<Todo>(`/todos/${id}`, todoData);
};

// Add more methods here
79 changes: 79 additions & 0 deletions src/components/NewTodoForm/NewTodoForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import React, { useState, useEffect } from 'react';
import type { Todo } from '../../types/Todo';
import { ErrorType } from '../../types/ErrorType';
import * as clientMethods from '../../api/todos';

type Props = {
onAdd: (value: Todo) => void;
onError: (message: ErrorType) => void;
setTempTodo: (tempTodo: Todo | null) => void;
inputFocusRef: React.RefObject<HTMLInputElement>;
};

export const NewTodoForm: React.FC<Props> = ({
onAdd,
onError,
setTempTodo,
inputFocusRef,
}) => {
const [title, setTitle] = useState('');
const [isSubmiting, setIsSubmiting] = useState(false);

useEffect(() => {
if (!isSubmiting) {
inputFocusRef.current?.focus();
}
}, [isSubmiting, inputFocusRef]);

const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
// 1. Validate
if (!title.trim()) {
onError(ErrorType.EmptyTitle);

return;
}

try {
setIsSubmiting(true);

setTempTodo({
id: 0,
userId: clientMethods.USER_ID,
title: title.trim(),
completed: false,
});

const createdTodo = await clientMethods.addTodo({
userId: clientMethods.USER_ID,
title: title.trim(),
completed: false,
});

onAdd(createdTodo);
onError(ErrorType.None);
setTitle('');
} catch {
onError(ErrorType.Add);
} finally {
setTempTodo(null);
setIsSubmiting(false);
}
// 2. Clear previous error
};

return (
<form onSubmit={handleSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={title}
onChange={event => setTitle(event.target.value)}
disabled={isSubmiting}
ref={inputFocusRef}
/>
</form>
);
};
1 change: 1 addition & 0 deletions src/components/NewTodoForm/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './NewTodoForm';
1 change: 1 addition & 0 deletions src/components/TodoItem/TodoItem.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// TodoItem styles
Loading
Loading