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 #1543

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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and implement the ability to toggle and rename todos.
## Toggling a todo status

Toggle the `completed` status on `TodoStatus` change:

- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save.
- covered the todo with a loader overlay while waiting for API response;
- the status should be changed on success;
Expand Down Expand Up @@ -38,6 +39,7 @@ Implement the ability to edit a todo title on double click:
- or the deletion error message if we tried to delete the todo.

## If you want to enable tests

- open `cypress/integration/page.spec.js`
- replace `describe.skip` with `describe` for the root `describe`

Expand All @@ -47,4 +49,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://Welbrn.github.io/react_todo-app-with-api/) and add it to the PR description.
199 changes: 185 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,197 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
/* eslint-disable jsx-a11y/label-has-associated-control */
import React, { useEffect, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
addTodos,
deleteTodos,
getTodos,
updateTodos,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { Filter } from './types/Filter';
import { Header } from './components/Header/Header';
import { TodoList } from './components/TodoList/TodoList';
import { Footer } from './components/Footer/Footer';
import { ErrorNotification } from './components/ErrorNotification/ErrorNotification';
import { filterTodos } from './utils/getFilteredTodos';
import { ErrorMessage } from './types/ErrorMessage';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorMessage | null>(null);
const [filterStatus, setFilterStatus] = useState<Filter>(Filter.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [editTodos, setEditTodos] = useState<number[]>([]);

const filteredTodos = filterTodos(todos, filterStatus);

const handleCreateTodo = async (newTodo: Omit<Todo, 'id'>) => {
setErrorMessage(null);
setTempTodo({ id: 0, ...newTodo });
setIsLoading(true);
try {
const createdTodo = await addTodos(newTodo);

setTodos(prev => [...prev, createdTodo]);
} catch (error) {
setErrorMessage(ErrorMessage.UnableToAdd);
throw error;
} finally {
setTempTodo(null);
setIsLoading(false);
}
};

const handleDeleteTodo = async (id: number) => {
setIsLoading(true);
setEditTodos(current => [...current, id]);
try {
await deleteTodos(id);
setTodos(prev => prev.filter(todo => todo.id !== id));
} catch {
setEditTodos([]);
setErrorMessage(ErrorMessage.UnableToDelete);
} finally {
setIsLoading(false);
}
};

const handleClearCompleted = async () => {
const completedTodos = todos.filter(todo => todo.completed);

await Promise.all(completedTodos.map(todo => handleDeleteTodo(todo.id)));
};

const handleToggleStatus = async (id: number, completed: boolean) => {
setIsLoading(true);
setEditTodos(current => [...current, id]);
try {
const todoToUpdate = todos.find(todo => todo.id === id);

if (!todoToUpdate) {
return;
}

const updatedTodo = await updateTodos(id, {
completed,
userId: todoToUpdate.userId,
title: todoToUpdate.title,
});

setTodos(prev =>
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)),
);
} catch {
setErrorMessage(ErrorMessage.UnableToUpdate);
} finally {
setEditTodos(prev => prev.filter(todoId => todoId !== id));
setIsLoading(false);
}
};

const handleToggleAll = async () => {
const allCompleted = todos.every(todo => todo.completed);
const newStatus = !allCompleted;

setIsLoading(true);
const promises = todos
.filter(todo => todo.completed !== newStatus)
.map(todo => handleToggleStatus(todo.id, newStatus));

try {
await Promise.all(promises);
setTodos(prev =>
prev.map(todo =>
todo.completed !== newStatus
? { ...todo, completed: newStatus }
: todo,
),
);
} catch {
setErrorMessage(ErrorMessage.UnableToUpdate);
} finally {
setIsLoading(false);
}
};

const handleUpdateTitle = async (id: number, newTitle: string) => {
setEditTodos(current => [...current, id]);

try {
const todoToUpdate = todos.find(todo => todo.id === id);

if (!todoToUpdate) {
return;
}

const updatedTodo = await updateTodos(id, {
...todoToUpdate,
title: newTitle,
});

setTodos(prev =>
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)),
);
} catch (error) {
setErrorMessage(ErrorMessage.UnableToUpdate);
throw error;
} finally {
setEditTodos(prev => prev.filter(todoId => todoId !== id));
}
};

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => setErrorMessage(ErrorMessage.UnableToLoad));
}, []);

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
todos={todos}
setErrorMessage={setErrorMessage}
handleCreateTodo={handleCreateTodo}
isLoading={isLoading}
onToggleAll={handleToggleAll}
/>

{todos.length > 0 && (
<TodoList
todos={filteredTodos}
tempTodo={tempTodo}
onDelete={handleDeleteTodo}
editTodos={editTodos}
onToggle={handleToggleStatus}
onUpdate={handleUpdateTitle}
/>
)}

{!!todos.length && (
<Footer
filterStatus={filterStatus}
setFilterStatus={setFilterStatus}
todos={todos}
handleClearCompleted={handleClearCompleted}
/>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
/>
</div>
);
};
20 changes: 20 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 2125;

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

Choose a reason for hiding this comment

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

let's move /todos into constant and reuse

};

export const addTodos = (newTodo: Omit<Todo, 'id'>) => {
return client.post<Todo>(`/todos`, newTodo);
};

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

export const updateTodos = (id: number, newTodo: Omit<Todo, 'id'>) => {
return client.patch<Todo>(`/todos/${id}`, newTodo);
};
42 changes: 42 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React, { Dispatch, SetStateAction, useEffect } from 'react';
import cn from 'classnames';
import { ErrorMessage } from '../../types/ErrorMessage';

type Props = {
errorMessage: ErrorMessage | null;
setErrorMessage: Dispatch<SetStateAction<ErrorMessage | null>>;
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => {
useEffect(() => {
if (errorMessage) {
const timer = setTimeout(() => {
setErrorMessage(null);
}, 3000);

return () => clearTimeout(timer);
}

return undefined;

Choose a reason for hiding this comment

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

do we really need to return undefined here?

}, [errorMessage, setErrorMessage]);

return (
<div
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !errorMessage,
})}
data-cy="ErrorNotification"
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage(null)}
/>
{errorMessage}
</div>
);
};
59 changes: 59 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react';
import { Todo } from '../../types/Todo';
import { Filter } from '../../types/Filter';
import cn from 'classnames';

type Props = {
todos: Todo[];
filterStatus: Filter;
setFilterStatus: (filter: Filter) => void;
handleClearCompleted: () => void;
};

const filterLinks = [
{ label: 'All', value: Filter.All },
{ label: 'Active', value: Filter.Active },
{ label: 'Completed', value: Filter.Completed },
];

export const Footer: React.FC<Props> = ({
setFilterStatus,
todos,
filterStatus,
handleClearCompleted,
}) => {
const todosLeft = todos.filter(todo => !todo.completed);
const isClearCompletedDisabled = todos.every(todo => !todo.completed);

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{todosLeft.length} items left
</span>

<nav className="filter" data-cy="Filter">
{filterLinks.map(({ label, value }) => (
<a
key={value}
href={`#/${value}`}
className={cn('filter__link', { selected: filterStatus === value })}
data-cy={`FilterLink${label}`}
onClick={() => setFilterStatus(value)}
>
{label}
</a>
))}
Comment on lines +35 to +45

Choose a reason for hiding this comment

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

that's good!

</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={isClearCompletedDisabled}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading