Skip to content
Open

Develop #2134

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://rekverr.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
196 changes: 180 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,190 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { useState, useEffect, useRef } from 'react';
import classNames from 'classnames';
import { TodoList } from './components/TodoList';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { USER_ID } from './api/todos';
import { HeaderTodo } from './components/HeaderTodo';
import { FilterTodo } from './components/FilterTodo';
import { useTodos } from './hooks/useTodos';
import { useErrorMessage } from './hooks/useErrorMessage';
import { filterTodos, FilterType } from './utils/todoFilters';
import { ErrorMessage } from './types/ErrorMessage';

export const App: React.FC = () => {
const [filter, setFilter] = useState<FilterType>(FilterType.ALL);
const [newTodoTitle, setNewTodoTitle] = useState('');
const { errorMessage, setErrorMessage } = useErrorMessage();

Choose a reason for hiding this comment

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

Consider making a custom type / enum for error states (e.g. ErrorMessage) and re-use it to avoid hard-coded typos

const {
todos,
isAdding,
deletingIds,
tempTodo,
isClearing,
handleAddTodo,
handleDeleteTodo,
handleClearCompleted,
handleCompletedTodo,
handleToggleAllTodos,
completingIds,
editingId,
editingIds,
editingTitle,
setEditingTitle,
handleStartEdit,
handleCommitEdit,
handleCancelEdit,
} = useTodos(setErrorMessage);

const inputRef = useRef<HTMLInputElement>(null);

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

useEffect(() => {
if (!isAdding && deletingIds.length === 0 && !isClearing) {
inputRef.current?.focus();
}
}, [isAdding, deletingIds.length, isClearing]);

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

const trimmedTitle = newTodoTitle.trim();

if (!trimmedTitle) {
setErrorMessage(ErrorMessage.EMPTY_TITLE);

return;
}

try {
await handleAddTodo(trimmedTitle, USER_ID);
setNewTodoTitle('');
} catch {
setErrorMessage(ErrorMessage.ADD_TODO);
}
};

const handleComplete = async (id: number, completed: boolean) => {
try {
await handleCompletedTodo(id, completed);
} catch {
setErrorMessage(ErrorMessage.UPDATE_TODO);
}
};

const handleToggleAll = async () => {
const hasActiveTodos = todos.some(todo => !todo.completed);

try {
await handleToggleAllTodos(hasActiveTodos);
} catch {
setErrorMessage(ErrorMessage.UPDATE_TODO);
}
};

const handleEditTodo = async (id: number, title: string) => {
let shouldDelete = false;

try {
shouldDelete = await handleCommitEdit(id, title);
} catch {
setErrorMessage(ErrorMessage.UPDATE_TODO);

return;
}

if (shouldDelete) {
try {
await handleDeleteTodo(id);
handleCancelEdit();
} catch {
setErrorMessage(ErrorMessage.DELETE_TODO);
}
}
};

const handleDelete = async (id: number) => {
try {
await handleDeleteTodo(id);
} catch {
setErrorMessage(ErrorMessage.DELETE_TODO);
}
};

const handleClear = async () => {
try {
await handleClearCompleted();
} catch (error) {
if (error instanceof Error) {
setErrorMessage(error.message);
}
}
};

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

const filteredTodos = filterTodos(todos, filter, tempTodo);

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">
<HeaderTodo
handlerSubmit={handleSubmit}
handleToggleAll={handleToggleAll}
inputRef={inputRef}
newTodoTitle={newTodoTitle}
setNewTodoTitle={setNewTodoTitle}
isAdding={isAdding}
todos={todos}
/>

<TodoList
todos={filteredTodos}
isAdding={isAdding}
deletingIds={deletingIds}
completingIds={completingIds}
editingId={editingId}
editingIds={editingIds}
editingTitle={editingTitle}
setEditingTitle={setEditingTitle}
handleDelete={handleDelete}
handleComplete={handleComplete}
handleStartEdit={handleStartEdit}
handleEditTodo={handleEditTodo}
handleCancelEdit={handleCancelEdit}
/>

<FilterTodo
todos={todos}
filter={filter}
setFilter={setFilter}
handleClearCompleted={handleClear}
/>
</div>

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

export const USER_ID = 4019;

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

export const addTodo = (title: string) => {
return client.post<Todo>(`/todos`, {
title,
userId: USER_ID,
completed: false,
});
};

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

export const completeTodo = (id: number, completed: boolean) => {
return client.patch<Todo>(`/todos/${id}`, { completed });
};

export const updateTodoTitle = (id: number, title: string) => {
return client.patch<Todo>(`/todos/${id}`, { title });
};
74 changes: 74 additions & 0 deletions src/components/FilterTodo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import classNames from 'classnames';
import { Todo } from '../types/Todo';
import { FilterType } from '../utils/todoFilters';

type Props = {
todos: Todo[];
filter: FilterType;
setFilter: (filter: FilterType) => void;
handleClearCompleted: () => void;
};

export const FilterTodo = ({
todos,
filter,
setFilter,
handleClearCompleted,
}: Props) => {
return (
<>
{todos.length > 0 && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{todos.filter(todo => !todo.completed).length} items left
</span>

<nav className="filter" data-cy="Filter">
<a
href="#/"
className={classNames('filter__link', {
selected: filter === FilterType.ALL,
})}
data-cy="FilterLinkAll"
onClick={() => setFilter(FilterType.ALL)}
>
All
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: filter === FilterType.ACTIVE,
})}
data-cy="FilterLinkActive"
onClick={() => setFilter(FilterType.ACTIVE)}
>
Active
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: filter === FilterType.COMPLETED,
})}
data-cy="FilterLinkCompleted"
onClick={() => setFilter(FilterType.COMPLETED)}
>
Completed
</a>
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!todos.some(todo => todo.completed)}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
)}
</>
);
};
Loading