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

solution #1578

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
8 changes: 4 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": "^1.9.12",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
319 changes: 305 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,317 @@
/* 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, { useEffect, useState } from 'react';
import { UserWarning } from './UserWarning';
import { Todo } from './types/Todo';
import { client } from './utils/fetchClient';
import { FilterTypes } from './types/FilterType';
import {
createTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import Header from './Components/Header';
import TodoList from './Components/TodoList';
import Footer from './Components/Footer';
import cn from 'classnames';

const USER_ID = 0;
interface OnDblClickParams {
index: number;
todo: Todo;
}

export const App: React.FC = () => {
const [todosDb, setTodosDb] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [todosToShow, setTodosToShow] = useState<Todo[]>([]);
const [error, setError] = useState<string | null>(null);
const [loadingTodoId, setLoadingTodoId] = useState<number[]>([]);
const [inputLoading, setInputLoading] = useState<boolean>(false);
const [editIndex, setEditIndex] = useState<number | null>(null);
const [editValue, setEditValue] = useState<string>('');
const [selectedFilter, setSelectedFilter] = useState<FilterTypes>(
FilterTypes.ALL,
);
const [newTodoTitle, setNewTodoTitle] = useState<string>('');

useEffect(() => {
setTodosToShow(
todosDb.filter(todo => {
switch (selectedFilter) {
case FilterTypes.ALL:
return true;
case FilterTypes.ACTIVE:
return !todo.completed;
case FilterTypes.COMPLETED:
return todo.completed;
default:
return true;
}
}),
);
}, [todosDb, selectedFilter]);

useEffect(() => {
const fetchTodos = async () => {
try {
setTodosDb(await getTodos());
} catch (err) {
setError('Unable to load todos');
}
};

fetchTodos();
}, []);

useEffect(() => {
const timeoutId = setTimeout(() => {
setError(null);
}, 3000);

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

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

const onEscape = () => {
setEditValue('');
setEditIndex(null);
};

const focusField = () => {
setTimeout(() => {
const inputField =
document.querySelector<HTMLInputElement>('.todoapp__new-todo');

inputField?.focus();
}, 0);
};

const deleteTodoFunc = async (id: number) => {
setLoadingTodoId(prevVal => [...prevVal, id]);
setError(null);
try {
await deleteTodo(id);
setTodosDb(todosDb.filter(todo => todo.id !== id));
focusField();
} catch (err) {
setError('Unable to delete a todo');
} finally {
setLoadingTodoId(prevVal => prevVal.filter(todoId => todoId !== id));
}
};

const completeTodo = async (id: number, completed: boolean) => {
setLoadingTodoId(prevVal => [...prevVal, id]);

setError(null);
try {
await updateTodo(id, { completed });
setTodosDb(
todosDb.map(todo => {
if (todo.id === id) {
return { ...todo, completed };
}

return todo;
}),
);
} catch (err) {
setError('Unable to update a todo');
} finally {
setLoadingTodoId(prevVal => prevVal.filter(todoId => todoId !== id));
}
};

const updateTodoFunc = async (
id: number,
title: string,
e?: React.FormEvent<HTMLFormElement>,
) => {
e?.preventDefault();
setLoadingTodoId(prevVal => [...prevVal, id]);

setError(null);
try {
const thisTodo = todosDb.find(todo => todo.id === id);

if (!title.trim()) {
// якщо title для зміни пустий
try {
await deleteTodo(id);
setEditIndex(null);
setEditValue('');
setTodosDb(todosDb.filter(todo => todo.id !== id));
} catch (err) {
setError('Unable to delete a todo');
}
} else if (!(thisTodo?.title === title.trim())) {
// якщо title для зміни не пустий і відрізняється від попереднього
await updateTodo(id, { title: title.trim() });
setTodosDb(
todosDb.map(todo => {
if (todo.id === id) {
return { ...todo, title: title.trim() };
}

return todo;
}),
);
setEditValue('');
setEditIndex(null);
} else if (thisTodo?.title === title.trim()) {
setEditIndex(null);
}

// onEscape();
} catch (err) {
setError('Unable to update a todo');
} finally {
setLoadingTodoId(prevVal => prevVal.filter(todoId => todoId !== id));
}
};

const addTodo = async (
e: React.FormEvent<HTMLFormElement>,
title: string,
) => {
e.preventDefault();
setError(null);
setInputLoading(true);
setTempTodo({
title: title.trim(),
completed: false,
id: 0,
userId: USER_ID,
});

if (!title.trim()) {
setInputLoading(false);
setError('Title should not be empty');

return;
}

try {
const todo = await createTodo(title);

setTodosDb([...todosDb, todo]);
setNewTodoTitle('');
} catch (err) {
setError('Unable to add a todo');
} finally {
focusField();
setInputLoading(false);
setTempTodo(null);
}
};

const onDblClick = ({ index, todo }: OnDblClickParams) => {
setEditIndex(index);
setEditValue(todo.title);
};

const clearCompleted = async () => {
setError(null);

const completedTodos = todosDb.filter(todo => todo.completed);

try {
const results = await Promise.allSettled(
completedTodos.map(todo =>
client.delete(`/todos/${todo.id}`).then(() => todo),
),
);

const successfulTodos = results
.filter(result => result.status === 'fulfilled')
.map(result => (result as PromiseFulfilledResult<Todo>).value);

const failedTodos = results
.filter(result => result.status === 'rejected')
.map((_, index) => completedTodos[index]);

setTodosDb(prevTodos =>
prevTodos.filter(
todo =>
!successfulTodos.some(
successfulTodo => successfulTodo.id === todo.id,
),
),
);

if (failedTodos.length > 0) {
setError('Unable to delete a todo');
}
} catch (err) {
setError('Unable to delete a todo');
} finally {
focusField();
}
};

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
todosDb={todosDb}
newTodoTitle={newTodoTitle}
setNewTodoTitle={setNewTodoTitle}
inputLoading={inputLoading}
addTodo={addTodo}
setError={setError}
completeTodo={completeTodo}
setTodosDb={setTodosDb}
/>

<TodoList
todosToShow={todosToShow}
editIndex={editIndex}
editValue={editValue}
setEditValue={setEditValue}
onDblClick={onDblClick}
onEscape={onEscape}
updateTodo={updateTodoFunc}
deleteTodo={deleteTodoFunc}
completeTodo={completeTodo}
loadingTodoId={loadingTodoId}
tempTodo={tempTodo}
/>
{todosDb.length > 0 && (
<Footer
todosDb={todosDb}
selectedFilter={selectedFilter}
setSelectedFilter={setSelectedFilter}
clearCompleted={clearCompleted}
/>
)}
</div>

{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}
<div
data-cy="ErrorNotification"
className={cn(
'notification is-danger is-light has-text-weight-normal',
{
hidden: !error,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(null)}
/>
{error}
</div>
</div>
);
};
Loading
Loading