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

Open
wants to merge 1 commit 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://polinabs.github.io/react_todo-app-with-api/) and add it to the PR description.
215 changes: 196 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,203 @@
/* 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 { UserWarning } from './UserWarning';

const USER_ID = 0;
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Header } from './copmonents/Header/Header';
import { TodoList } from './copmonents/TodoList/TodoList';
import { Footer } from './copmonents/Footer/Footer';
import { Todo } from './types/Todo';
import * as todoMethods from './api/todos';
import { ErrorNotification } from './copmonents/Error/Error';
import { FilterStatus } from './types/FilterStatus';
import getTodosFilter from './utils/getTodosFilter';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [filterStatus, setFilterStatus] = useState<FilterStatus>(
FilterStatus.All,
);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [deletingTodoIds, setDeletingTodoIds] = useState<number[] | null>(null);
const [updatingTodoIds, setUpdatingTodoIds] = useState<number[] | null>(null);
const [isInputDisabled, setInputDisabled] = useState(false);

const isTodosEmpty = todos.length === 0;
const todosActiveQuantity = todos.filter(todo => !todo.completed).length;
const todosComplitedQuantity = todos.filter(todo => todo.completed).length;
const allTodosIsComplited = todos.every(todo => todo.completed);
const inputRef = useRef<HTMLInputElement>(null);

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

useEffect(() => {
todoMethods
.getTodos()
.then(setTodos)
.catch(error => {
setErrorMessage('Unable to load todos');
throw error;
});
}, []);

const filteredTodos = useMemo((): Todo[] => {
const filterTodos = getTodosFilter(filterStatus);

if (!filterTodos) {
return todos;
}

return filterTodos(todos);
}, [filterStatus, todos]);

const addTodo = async (title: string): Promise<void> => {
const userId = todoMethods.USER_ID;

const temporaryTodo: Todo = {
id: 0,
userId,
title,
completed: false,
};

setTempTodo(temporaryTodo);
setInputDisabled(true);

try {
const newTodo = await todoMethods.createTodo({
userId,
title,
completed: false,
});

setTodos(currentTodos => [...currentTodos, newTodo]);
setTempTodo(null);
} catch (error) {
setErrorMessage('Unable to add a todo');
setTempTodo(null);
throw error;
} finally {
setTempTodo(null);
setInputDisabled(false);
}
};

const deleteTodo = async (todoId: number): Promise<void> => {
setDeletingTodoIds(prev => (prev ? [...prev, todoId] : [todoId]));
setInputDisabled(true);

try {
await todoMethods.deleteTodo(todoId);

setTodos(currentTodos => currentTodos.filter(todo => todo.id !== todoId));
} catch (error) {
setErrorMessage('Unable to delete a todo');
throw error;
} finally {
setDeletingTodoIds(prev =>
prev ? prev.filter(id => id !== todoId) : [],
);
setInputDisabled(false);
}
};

const clearAllComplitedTodos = () => {
const completedTodoIds = todos
.filter(todo => todo.completed)
.map(todo => todo.id);

if (completedTodoIds.length === 0) {
return;
}

setDeletingTodoIds(completedTodoIds);
setInputDisabled(true);

const deleteTodoPromises = completedTodoIds.map(deleteTodo);

Promise.all(deleteTodoPromises).finally(() => {
setDeletingTodoIds(null);
setInputDisabled(false);
});
};

const updateTodo = async (todo: Todo) => {
setUpdatingTodoIds(prev => (prev ? [...prev, todo.id] : [todo.id]));

try {
const updatedTodo = await todoMethods.updateTodo(todo);

setTodos(currentTodos =>
currentTodos.map(currentTodo => {
if (currentTodo.id === updatedTodo.id) {
return updatedTodo;
}

return currentTodo;
}),
);
} catch (error) {
setErrorMessage('Unable to update a todo');
throw error;
} finally {
setUpdatingTodoIds(prev =>
prev ? prev.filter(id => id !== todo.id) : [],
);
}
};

const toggleTodos = async () => {
const targetStatus = !allTodosIsComplited;

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

try {
for (const todo of todosToUpdate) {
await updateTodo({ ...todo, completed: targetStatus });
}
} catch (error) {
setErrorMessage('Unable to update a todo');
throw error;
}
};

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
addTodo={addTodo}
setErrorMessage={setErrorMessage}
isInputDisabled={isInputDisabled}
inputRef={inputRef}
allTodosIsComplited={allTodosIsComplited}
isTodosEmpty={isTodosEmpty}
toggleTodos={toggleTodos}
/>
<TodoList
todos={filteredTodos}
deleteTodo={deleteTodo}
deletingTodoIds={deletingTodoIds}
updatingTodoIds={updatingTodoIds}
tempTodo={tempTodo}
updateTodo={updateTodo}
/>
{todos.length > 0 && (
<Footer
setFilterStatus={setFilterStatus}
filterStatus={filterStatus}
todosActiveQuantity={todosActiveQuantity}
todosComplitedQuantity={todosComplitedQuantity}
clearAllComplitedTodos={clearAllComplitedTodos}
/>
)}
</div>

<ErrorNotification error={errorMessage} setError={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 = 2214;

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

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

export const createTodo = ({ userId, title, completed }: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', { userId, title, completed });
};

export const updateTodo = (todo: Todo) => {
return client.patch<Todo>(`/todos/${todo.id}`, todo);
};
43 changes: 43 additions & 0 deletions src/copmonents/Error/Error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import classNames from 'classnames';
import React, { useEffect } from 'react';

type Props = {
error: string;
setError: (error: string) => void;
};

export const ErrorNotification: React.FC<Props> = ({ error, setError }) => {
useEffect(() => {
if (!error) {
return;
}

const timerId = setTimeout(() => {
setError('');
}, 3000);

return () => {
clearTimeout(timerId);
};
}, [error, setError]);

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={() => setError('')}
/>
{error}
</div>
);
};
59 changes: 59 additions & 0 deletions src/copmonents/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import classNames from 'classnames';
import { FilterStatus } from '../../types/FilterStatus';
import capitalize from '../../utils/capitalize';

type Props = {
setFilterStatus: (link: FilterStatus) => void;
filterStatus: FilterStatus;
todosActiveQuantity: number;
todosComplitedQuantity: number;
clearAllComplitedTodos: () => void;
};

const formatFilterStatusHref = (filterStatus: FilterStatus): string => {
return `#/${filterStatus === FilterStatus.All ? '' : filterStatus}`;
};

export const Footer: React.FC<Props> = ({
setFilterStatus,
filterStatus,
todosActiveQuantity,
todosComplitedQuantity,
clearAllComplitedTodos,
}) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{todosActiveQuantity} items left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(FilterStatus).map(status => {
return (
<a
href={formatFilterStatusHref(status)}
className={classNames('filter__link', {
selected: filterStatus === status,
})}
data-cy={`FilterLink${capitalize(status)}`}
onClick={() => setFilterStatus(status)}
key={status}
>
{capitalize(status)}
</a>
);
})}
</nav>

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