Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add task solution #1497

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
304 changes: 284 additions & 20 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,290 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';
import { FC, useCallback, useEffect, useMemo, useState } from 'react';
import {
getTodos,
addTodo,
deleteTodo,
USER_ID,
toggleTodo,
updateTodoTitle,
} from './api/todos';
import { Todo } from './types/Todo';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { FilterStates, ErrorMessages } from './types/enums';
import { TodoItem } from './components/TodoItem';

const USER_ID = 0;
export const App: FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [error, setError] = useState<ErrorMessages>(ErrorMessages.DEFAULT);
const [filter, setFilter] = useState(FilterStates.ALL);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [title, setTitle] = useState('');
const [isAdding, setIsAdding] = useState(false);
const [isEditingId, setIsEditingId] = useState<number | null>(null);

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const trimmedTitle = title.trim();

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

setTodos(data);
} catch (err) {
setError(ErrorMessages.LOAD_TODOS);
const timer = setTimeout(() => setError(ErrorMessages.DEFAULT), 3000);

return () => clearTimeout(timer);
}
};

const handleAddTodo = useCallback(async (): Promise<void> => {
if (trimmedTitle === '') {
setError(ErrorMessages.NAMING_TODOS);
}

setIsAdding(true);

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

setTempTodo(newTempTodo);

const newTodo = await addTodo(trimmedTitle);

setTodos(prevTodos => [...prevTodos, newTodo]);
setTempTodo(null);
setTitle('');
} catch {
setError(ErrorMessages.ADDING_TODOS);
setTempTodo(null);
} finally {
setIsAdding(false);
setTimeout(() => {
const input =
document.querySelector<HTMLInputElement>('.todoapp__new-todo');

input?.focus();
}, 100);
}
}, [title]);

Check warning on line 75 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

React Hook useCallback has a missing dependency: 'trimmedTitle'. Either include it or remove the dependency array

const handleDeleteTodo = useCallback(
async (todoId: number): Promise<void> => {
try {
await deleteTodo(todoId);
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== todoId));
} catch {
setError(ErrorMessages.DELETING_TODOS);
} finally {
const input =
document.querySelector<HTMLInputElement>('.todoapp__new-todo');

input?.focus();
}
},
[],
);

const handleToggleTodoStatus = useCallback(
async (todoId: number, completed: boolean): Promise<void> => {
try {
await toggleTodo(todoId, completed);
setTodos(prevTodos =>
prevTodos.map(todo =>
todo.id === todoId ? { ...todo, completed } : todo,
),
);
} catch {
setError(ErrorMessages.UPDATE_TODOS);
}
},
[],
);

const handleUpdateTodoTitle = useCallback(
async (todoId: number, newTitle: string): Promise<void> => {
const existingTodo = todos.find(todo => todo.id === todoId);
const newTitleTrimmed = newTitle.trim();

if (!existingTodo) {
return;
}

if (newTitleTrimmed === existingTodo.title) {
setIsEditingId(null);

return;
}

if (newTitleTrimmed === '') {
try {
await deleteTodo(todoId);
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== todoId));
setIsEditingId(null);
} catch {
setError(ErrorMessages.DELETING_TODOS);
}

return;
}

try {
await updateTodoTitle(todoId, newTitle);
setTodos(prevTodos =>
prevTodos.map(todo =>
todo.id === todoId ? { ...todo, title: newTitle } : todo,
),
);
setIsEditingId(null);
} catch {
setError(ErrorMessages.UPDATE_TODOS);
}
},
[todos],
);

const handleDoubleClick = useCallback((todoId: number) => {
setIsEditingId(todoId);
}, []);

const filteredTodos = useMemo(() => {
return todos.filter(todo => {
switch (filter) {
case FilterStates.ACTIVE:
return !todo.completed;
case FilterStates.COMPLETED:
return todo.completed;
default:
return true;
}
});
}, [todos, filter]);

const hasTodos = todos.length > 0;
const allCompleted = todos.length > 0 && todos.every(todo => todo.completed);

const handleToggleAllTodos = useCallback(async () => {
const newCompletedState = !allCompleted;

try {
const updatePromises = todos.map(async todo => {
if (todo.completed !== newCompletedState) {
await toggleTodo(todo.id, newCompletedState);

return { ...todo, completed: newCompletedState };
}

return todo;
});

const updatedTodos = await Promise.all(updatePromises);

setTodos(updatedTodos);
} catch {
setError(ErrorMessages.UPDATE_TODOS);
const timer = setTimeout(() => setError(ErrorMessages.DEFAULT), 3000);

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

const handleClearCompleted = useCallback(async (): Promise<void> => {
const completedTodos = todos.filter(todo => todo.completed);

try {
const deletionResults = await Promise.allSettled(
completedTodos.map(todo => handleDeleteTodo(todo.id)),
);

const hasErrors = deletionResults.some(
result => result.status === 'rejected',
);

if (hasErrors) {
setError(ErrorMessages.DELETING_SOME_TODOS);
}
} catch {
setError(ErrorMessages.CLEAR_COMPLETED_TODOS);
}
}, [handleDeleteTodo, todos]);

const handleHideError = () => {
setError(ErrorMessages.DEFAULT);
};

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

useEffect(() => {
if (error) {
const timeout = setTimeout(() => {
setError(ErrorMessages.DEFAULT);
}, 3000);

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

Check warning on line 233 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

React Hook useEffect has an unnecessary dependency: 'ErrorMessages'. Either exclude it or remove the dependency array. Outer scope values like 'ErrorMessages' aren't valid dependencies because mutating them doesn't re-render the component

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
allCompleted={allCompleted}
onAddTodo={handleAddTodo}
onToggleAllTodos={handleToggleAllTodos}
title={title}
setTitle={setTitle}
todoCount={todos.length}
isAdding={isAdding}
setError={setError}
/>

{hasTodos &&
filteredTodos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onDelete={handleDeleteTodo}
onToggleStatus={handleToggleTodoStatus}
onUpdateTitle={handleUpdateTodoTitle}
setError={setError}
isEditing={isEditingId === todo.id}
setIsEditing={setIsEditingId}
onDoubleClick={() => handleDoubleClick(todo.id)}
error={error}
/>
))}

{tempTodo && (
<TodoItem
todo={tempTodo}
onDelete={handleDeleteTodo}
onToggleStatus={handleToggleTodoStatus}
onUpdateTitle={handleUpdateTodoTitle}
setError={setError}
isAdding={isAdding}
error={error}
/>
)}

{hasTodos && (
<Footer
todos={todos}
filter={filter}
setFilter={setFilter}
onClearCompleted={handleClearCompleted}
/>
)}
</div>
<ErrorNotification error={error} onHideError={handleHideError} />
</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 = 1625;

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 = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};

export const toggleTodo = (todoId: number, completed: boolean) => {
return client.patch(`/todos/${todoId}`, { completed });
};

export const updateTodoTitle = (todoId: number, title: string) => {
return client.patch(`/todos/${todoId}`, { title });
};
36 changes: 36 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { FC } from 'react';
import classNames from 'classnames';
import { ErrorMessages } from '../types/enums';

interface ErrorNotificationProps {
error: ErrorMessages;
onHideError: () => void;
}

export const ErrorNotification: FC<ErrorNotificationProps> = ({
error,
onHideError,
}) => {
return (
<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={onHideError}
/>
{error}
</div>
);
};
Loading
Loading