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

Done #1572

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open

Done #1572

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://IrynaMariiko00.github.io/react_todo-app-with-api/) and add it to the PR description.
5,184 changes: 3,033 additions & 2,151 deletions package-lock.json

Large diffs are not rendered by default.

254 changes: 238 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,248 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState, useMemo, useRef } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { Header } from './components/Header';
import { Todo } from './types/Todo';
import {
getTodos,
addTodos,
deleteTodos,
USER_ID,
updateTodos,
} from './api/todos';
import { TodoItem } from './components/TodoItem';
import { Errors } from './components/Errors';
import { Footer } from './components/Footer';
import { filterTodos } from './utils/FilterTodo';
import { FilterBy } from './types/FilterBy';
import { ErrorMessage } from './types/ErrorMessage';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [error, setError] = useState('');
const [currentFilter, setCurrentFilter] = useState<FilterBy>(FilterBy.All);
const [currentTodoIds, setCurrentTodoIds] = useState<number[]>([]);
const [isInputDisabled, setIsInputDisabled] = useState(false);
const [query, setQuery] = useState('');
const inputRef = useRef<HTMLInputElement | null>(null);

useEffect(() => {
setError('');

getTodos()
.then(setTodos)
.catch(() => {
setError('Unable to load todos');
});
}, []);

const filtered = useMemo(
() => filterTodos(todos, currentFilter),
[todos, currentFilter],
);

const handleNewTodo = (newTodo: Todo) => {
const newTodoWithStatus = { ...newTodo, isPending: true };
const newTodosList = [...todos, newTodoWithStatus];

setIsInputDisabled(true);
setCurrentTodoIds([...currentTodoIds, newTodo.id]);
setTodos(newTodosList);

addTodos(newTodo)
.then(todoFromServer => {
setTodos(currentTodos =>
currentTodos.map(todo =>
todo.id === newTodo.id
? { ...todo, id: todoFromServer.id, isPending: false }
: todo,
),
);
setQuery('');
})
.catch(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== newTodo.id),
);
setError(ErrorMessage.Add);
})
.finally(() => {
setCurrentTodoIds([]);
setIsInputDisabled(false);
});
};

const handleDeleteTodo = (todoId: number) => {
setCurrentTodoIds([...currentTodoIds, todoId]);
deleteTodos(todoId)
.then(() => {
setTodos(todos.filter(todo => todo.id !== todoId));
})
.catch(() => setError(ErrorMessage.Delete))
.finally(() => setCurrentTodoIds([]));
};

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

const activeTodos = todos.filter(todo => !todo.completed && !todo.isPending);

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

const failedDeletions: Todo[] = [];

Promise.all(
completedTodos.map(todo =>
deleteTodos(todo.id).catch(() => {
failedDeletions.push(todo);
}),
),
).finally(() => {
if (failedDeletions.length) {
setError(ErrorMessage.Delete);
}

const newTodos = todos.filter(
todo =>
!todo.completed ||
failedDeletions.some(failed => failed.id === todo.id),
);

setTodos(newTodos);
});
};

const isToggleAllActive = todos.every(todo => todo.completed);

const handleToggleAll = () => {
let updatedTodos: Todo[];

setCurrentTodoIds(todos.map(todo => todo.id));

if (isToggleAllActive) {
updatedTodos = todos.map(todo => ({
...todo,
completed: false,
}));
} else {
updatedTodos = todos
.filter(todo => !todo.completed)
.map(todo => ({
...todo,
completed: true,
}));
}

Promise.all(updatedTodos.map(todo => updateTodos(todo)))
.then(() => {
if (isToggleAllActive) {
setTodos(updatedTodos);
} else {
setTodos(prevTodos =>
prevTodos.map(todo => {
if (isToggleAllActive) {
return todo;
}

return { ...todo, completed: true };
}),
);
}
})
.catch(() => {
setError(ErrorMessage.UpdateTodo); //
setTodos(prevTodos => prevTodos);
})
.finally(() => setCurrentTodoIds([]));
};

const toggleTodoStatus = (updatedTodo: Todo) => {
const updatedTodoCopy = { ...updatedTodo };

setCurrentTodoIds([...currentTodoIds, updatedTodoCopy.id]);

updatedTodoCopy.completed = !updatedTodoCopy.completed;
updateTodos(updatedTodoCopy)
.then(() => {
setTodos(currentTodo =>
currentTodo.map(todo =>
todo.id === updatedTodoCopy.id
? { ...todo, completed: updatedTodoCopy.completed }
: todo,
),
);
})
.catch(() => {
setError(ErrorMessage.UpdateTodo);
setTodos(prevTodos => prevTodos);
})
.finally(() => setCurrentTodoIds([]));
};

const handleRenamingTodo = (renamedTodo: Todo) => {
setCurrentTodoIds([...currentTodoIds, renamedTodo.id]);

return updateTodos(renamedTodo)
.then(() => {
setTodos(prevTodos =>
prevTodos.map(todo =>
todo.id === renamedTodo.id ? renamedTodo : todo,
),
);
})
.catch(() => setError(ErrorMessage.UpdateTodo))
.finally(() => setCurrentTodoIds([]));
};

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
onTodo={handleNewTodo}
onError={setError}
isInputDisabled={isInputDisabled}
query={query}
setQuery={setQuery}
inputRef={inputRef}
handleToggleAll={handleToggleAll}
isToggleAllActive={isToggleAllActive}
todos={todos}
/>

<section className="todoapp__main" data-cy="TodoList">
{filtered.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onToggleStatus={toggleTodoStatus}
handleDeleteTodo={handleDeleteTodo}
isLoading={currentTodoIds.includes(todo.id)}
onRenamingTodo={handleRenamingTodo}
/>
))}
</section>

{todos.length !== 0 && (
<Footer
currentFilter={currentFilter}
setCurrentFilter={setCurrentFilter}
todos={todos}
handleClearCompleted={handleClearCompleted}
activeTodos={activeTodos}
/>
)}
</div>

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

export const USER_ID = 2177;

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

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

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

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

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

export const Errors: React.FC<Props> = ({ error, onClearError }) => {
useEffect(() => {
if (error) {
setTimeout(() => {
onClearError('');
}, 3000);
}
}, [error, onClearError]);

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={() => onClearError('')}
/>
{error}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/Errors/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Errors';
Loading
Loading