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

Develop #1535

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

Develop #1535

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://OkMoroz.github.io/react_todo-app-with-api/) and add it to the PR description.
198 changes: 179 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,186 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';
import React, { useState, useEffect } from 'react';
import { addTodo, deleteTodo, getTodos, updateTodo } from './api/todos';

const USER_ID = 0;
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { Errors } from './components/Errors';

import { loadingObject } from './utils/loadingObject';
import { filteredTodos } from './utils/filteredTodos';

import { Todo } from './types/Todo';
import { ErrorMessage } from './types/enum/Errors';
import { Loading } from './types/Loading';
import { Filters } from './types/enum/Filters';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorMessage>(
ErrorMessage.Default,
);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [filter, setFilter] = useState<Filters>(Filters.All);
const [loadingId, setLoadingId] = useState<Loading>({});

Choose a reason for hiding this comment

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

краще зберігати саму id, без об'єкта і судячи з назви там має бути id

useEffect(() => {
const timeoutId = setTimeout(
() => setErrorMessage(ErrorMessage.Default),
3000,
);

getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage(ErrorMessage.UnableToLoad);
clearTimeout(timeoutId);
});

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

const handleAdd = (newTodo: Todo): Promise<void> => {
setTempTodo(newTodo);

return addTodo(newTodo).then(newTodoRes => {
setTodos(currentTodos => [...currentTodos, newTodoRes]);
});
};

const updateCompleted = (
updatedTodo: Todo,
key: keyof Todo,
value: boolean | string,
) => {
return updateTodo({ ...updatedTodo, [key]: value })
.then((updatedTodoFromServer: Todo) => {
setTodos(currentTodos => {
return currentTodos.map(todo =>
todo.id === updatedTodo.id ? updatedTodoFromServer : todo,
);
});

return false;
})
.catch(() => {
setErrorMessage(ErrorMessage.UnableToUpdate);

return true;
});
};

const handleToggleAll = () => {
const activeTodos = todos.filter(todo => !todo.completed);
const activeTodosIds = loadingObject(activeTodos);

if (activeTodos.length) {
setLoadingId(activeTodosIds);

Promise.all(
activeTodos.map(todo => updateTodo({ ...todo, completed: true })),
)
.then(() =>
setTodos(currentTodos => {
return currentTodos.map(todo => {
if (Object.hasOwn(activeTodosIds, todo.id)) {
return { ...todo, completed: true };
} else {
return todo;
}
});
}),
)
.catch(() => setErrorMessage(ErrorMessage.UnableToUpdate))
.finally(() => setLoadingId({}));

return;
}

setLoadingId(loadingObject(todos));
Promise.all(todos.map(todo => updateTodo({ ...todo, completed: false })))
.then(() =>
setTodos(prevTodos => {
return prevTodos.map(todo => ({ ...todo, completed: false }));
}),
)
.catch(() => setErrorMessage(ErrorMessage.UnableToUpdate))
.finally(() => setLoadingId({}));
};

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

setLoadingId(loadingObject(completedTodos));

Promise.allSettled(
completedTodos.map(todo => deleteTodo(todo.id).then(() => todo)),
)
.then(values => {
values.map(val => {
if (val.status === 'rejected') {
setErrorMessage(ErrorMessage.UnableToDelete);
} else {
setTodos(currentTodos => {
const todoId = val.value as Todo;

return currentTodos.filter(todo => todo.id !== todoId.id);
});
}
});
})
.finally(() => setLoadingId({}));
};

const handleDelete = (todoId: number): Promise<void> => {
return deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.UnableToDelete);
})
.finally(() => setTempTodo(null));
};

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
tempTodo={tempTodo}
todos={todos}
onToggleAll={handleToggleAll}
onChangeTempTodo={setTempTodo}
setErrorMessage={setErrorMessage}
onSubmit={handleAdd}
/>

<TodoList
todos={filteredTodos(todos, filter)}
tempTodo={tempTodo}
loadingId={loadingId}
onEdit={updateCompleted}
onDelete={handleDelete}
/>

{!!todos.length && (
<Footer
todos={todos}
selectedFilter={filter}
onFilteredStatus={setFilter}
onDeleteCompleted={handleDeleteCompleted}
setLoadingId={setLoadingId}
/>
)}
</div>

<Errors
message={errorMessage}
clearError={() => setErrorMessage(ErrorMessage.Default)}
/>
</div>
);
};
2 changes: 2 additions & 0 deletions src/api/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const USER_ID = 2132;
export const TODOS_ENDPOINT = '/todos';
19 changes: 19 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';
import { USER_ID, TODOS_ENDPOINT } from './constants';

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

export const addTodo = (data: Omit<Todo, 'id'>) => {
return client.post<Todo>(TODOS_ENDPOINT, data);
};

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

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

type Props = {
message: string;
clearError: () => void;
};

export const Errors: React.FC<Props> = props => {
const { message, clearError } = props;

useEffect(() => {
const timeOut = setTimeout(clearError, 3000);

return () => {
clearTimeout(timeOut);
};
}, [message]);

Check warning on line 18 in src/components/Errors.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

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

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

type Props = {
todos: Todo[];
selectedFilter: Filters;
onFilteredStatus: (filter: Filters) => void;
onDeleteCompleted: () => void;
setLoadingId: React.Dispatch<React.SetStateAction<Loading>>;
};

export const Footer: React.FC<Props> = props => {
const {
todos,
selectedFilter,
onFilteredStatus,
onDeleteCompleted,
setLoadingId,
} = props;
// const [isLoading, setIsLoading] = useState(false);

const filtersValue = useMemo(() => Object.values(Filters), []);
const activeTodosCount = useMemo(
() => todos.filter(todo => !todo.completed).length,
[todos],
);
const isCompleted = useMemo(
() => todos.some(todo => todo.completed),
[todos],
);
let isDeleteCompleted = false;

Choose a reason for hiding this comment

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

loading state?


const handleDeleteCompleted = () => {
setLoadingId({});
isDeleteCompleted = true;
onDeleteCompleted();
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodosCount} items left
</span>
<nav className="filter" data-cy="Filter">
{filtersValue.map(filter => (
<a
key={filter}
href={`#/${filter !== Filters.All && filter.toLowerCase()}`}
className={cn('filter__link', {
selected: filter === selectedFilter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => onFilteredStatus(filter)}
>
{filter}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={isDeleteCompleted || !isCompleted}
style={{ visibility: !isCompleted ? 'hidden' : 'visible' }}
onClick={handleDeleteCompleted}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading