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

Initital solution #1493

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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,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://v1rnt.github.io/react_todo-app-with-api/) and add it to the PR description.
182 changes: 163 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,170 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { deleteTodo, getTodos, patchTodo } from './api/todos';

const USER_ID = 0;
import { Todo } from './types/Todo';
import { Filter } from './types/Filter';
import { Errors } from './types/Errors';

import { Footer } from './components/Footer';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { ErrorMessage } from './components/ErrorMessage';

import { handleError } from './utils/handleError';
import { getFilteredTodos } from './utils/getFilteredTodos';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todosFromServer, setTodosFromServer] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<Errors>(Errors.Default);
const [filterOption, setFilterOption] = useState<Filter>(Filter.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [deletionIds, setDeletionIds] = useState<number[]>([]);
const [pendingTodos, setPendingTodos] = useState<Todo[]>([]);

const completedTodoIds = useMemo(() => {
return todosFromServer.filter(todo => todo.completed).map(todo => todo.id);
}, [todosFromServer]);

const uncompletedTodos = useMemo(() => {
return todosFromServer.filter(todo => !todo.completed);
}, [todosFromServer]);

const uncompletedTodosAmount = uncompletedTodos.length;

const filteredTodos = useMemo(() => {
return getFilteredTodos(todosFromServer, filterOption);
}, [todosFromServer, filterOption]);

const handleDeleteTodos = useCallback((ids: number[]) => {
Promise.all(
ids.map(id => {
setDeletionIds(current => [...current, id]);

deleteTodo(id)
.then(() => {
setTodosFromServer(current =>
current.filter(todo => todo.id !== id),
);
})
.catch(() => {
handleError(setErrorMessage, Errors.DeleteTodo);
})
.finally(() =>
setDeletionIds(currIds => currIds.filter(currId => currId !== id)),
);
}),
);
}, []);

const handleChangeTodos = useCallback(
(newTodos: Todo[]) => {
return Promise.all(
newTodos.map(todo => {
setPendingTodos(current => [...current, todo]);

const { id, ...todoBody } = todo;

return patchTodo(todoBody, id)
.then(() => {
setTodosFromServer(current =>
current.map(currentTodo => {
return currentTodo.id !== todo.id ? currentTodo : todo;
}),
);
})
.catch(() => {
handleError(setErrorMessage, Errors.UpdateTodo);
throw new Error(errorMessage);
})
.finally(() => setPendingTodos([]));
}),
);
},
[errorMessage],
);

const handleToggleCompleted = (id: number, updatedField: Partial<Todo>) => {
setPendingTodos(current => [...current]);

return patchTodo(updatedField, id)
.then((updatedTodo: Todo) =>
setTodosFromServer(current =>
current.map(todo => (todo.id === id ? updatedTodo : todo)),
),
)
.catch(() => {
handleError(setErrorMessage, Errors.UpdateTodo);
throw new Error(errorMessage);
})
.finally(() =>
setPendingTodos(current => current.filter(todo => todo.id !== id)),
);
};

const handleToggleCompletedAll = () => {
if (uncompletedTodos && uncompletedTodosAmount) {
Promise.allSettled(
uncompletedTodos.map(({ id }) =>
handleToggleCompleted(id, { completed: true }),
),
);
} else {
Promise.allSettled(
todosFromServer.map(({ id }) =>
handleToggleCompleted(id, { completed: false }),
),
);
}
};

useEffect(() => {
getTodos()
.then(setTodosFromServer)
.catch(() => handleError(setErrorMessage, Errors.LoadingTodos));
}, []);
Comment on lines +121 to +123

Choose a reason for hiding this comment

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

It's better to move the logic inside the useEffect hook to a separate function, as it improves code readability, reusability, and makes testing easier. It also helps keep useEffect focused on side effects.


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
setTodos={setTodosFromServer}
setError={setErrorMessage}
setTempTodo={setTempTodo}
tempTodo={tempTodo}
uncompletedTodosAmount={uncompletedTodosAmount}
todos={todosFromServer}
onToggleCompletedAll={handleToggleCompletedAll}
/>

{!!todosFromServer.length && (
<>
<TodoList
todos={filteredTodos}
tempTodo={tempTodo}
deletionIds={deletionIds}
pendingTodos={pendingTodos}
errorMessage={errorMessage}
onTodosChange={handleChangeTodos}
onDeleteTodos={handleDeleteTodos}
/>
<Footer
filterOption={filterOption}
completedTodoIds={completedTodoIds}
uncompletedTodosAmount={uncompletedTodosAmount}
setFilterOption={setFilterOption}
setDeletionIds={setDeletionIds}
onDeleteTodos={handleDeleteTodos}
/>
</>
)}
</div>

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

export const USER_ID = 1606;

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

export const postTodo = (todo: Omit<Todo, 'id'>): Promise<Todo> =>
client.post<Todo>('/todos', todo);

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

export const patchTodo = (props: Partial<Todo>, id: number): Promise<Todo> =>
client.patch<Todo>(`/todos/${id}`, props);
28 changes: 28 additions & 0 deletions src/components/ErrorMessage/ErrorMessage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { FC, Dispatch } from 'react';
import cn from 'classnames';
import { Errors } from '../../types/Errors';

type Props = {
errorMessage: Errors;
setErrorMessage: Dispatch<React.SetStateAction<Errors>>;
};

export const ErrorMessage: FC<Props> = ({ errorMessage, setErrorMessage }) => {
return (
<div
data-cy="ErrorNotification"
// eslint-disable-next-line max-len
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !errorMessage,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className={cn('delete', { hidden: !errorMessage })}
onClick={() => setErrorMessage(Errors.Default)}
/>
{errorMessage}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorMessage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorMessage';
56 changes: 56 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { FC, Dispatch, SetStateAction } from 'react';
import { Filter } from '../../types/Filter';
import cn from 'classnames';

type Props = {
completedTodoIds: number[];
uncompletedTodosAmount: number;
filterOption: Filter;
setFilterOption: Dispatch<SetStateAction<Filter>>;
setDeletionIds: Dispatch<SetStateAction<number[]>>;
onDeleteTodos: (ids: number[]) => void;
};

export const Footer: FC<Props> = ({
completedTodoIds,
uncompletedTodosAmount,
filterOption,
setFilterOption,
onDeleteTodos,
}) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{uncompletedTodosAmount} items left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(Filter).map(filter => {
return (
<a
href={filter === 'All' ? '#/' : `#/${filter.toLowerCase()}`}
className={cn('filter__link', {
selected: filter === filterOption,
})}
data-cy={`FilterLink${filter}`}
key={filter}
onClick={() => setFilterOption(filter)}
>
{filter}
</a>
);
})}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={() => onDeleteTodos(completedTodoIds)}
disabled={!completedTodoIds.length}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/components/Footer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Footer';
96 changes: 96 additions & 0 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import {
FC,
Dispatch,
SetStateAction,
useRef,
useEffect,
useState,
} from 'react';
import cn from 'classnames';
import { InputForm } from '../InputForm';
import { Todo } from '../../types/Todo';
import { Errors } from '../../types/Errors';
import { handleError } from '../../utils/handleError';
import { postTodo, USER_ID } from '../../api/todos';

type Props = {
todos: Todo[];
tempTodo: Todo | null;
uncompletedTodosAmount: number;
setTempTodo: Dispatch<SetStateAction<Todo | null>>;
setError: Dispatch<SetStateAction<Errors>>;
setTodos: Dispatch<SetStateAction<Todo[]>>;
onToggleCompletedAll: () => void;
};

export const Header: FC<Props> = ({
todos,
tempTodo,
uncompletedTodosAmount,
setTempTodo,
setError,
setTodos,
onToggleCompletedAll,
}) => {
const [inputValue, setInputValue] = useState('');
const inputRef = useRef<HTMLInputElement | null>(null);

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

const trimmedInputValues = inputValue.trim();

if (!trimmedInputValues) {
handleError(setError, Errors.EmptyTitle);

return;
}

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

setTempTodo(temporaryTodo);

postTodo(temporaryTodo)
.then(res => {
setTodos(current => [...current, res]);
setInputValue('');
setTempTodo(null);
})
.catch(() => {
setTempTodo(null);
handleError(setError, Errors.AddTodo);
});
};

useEffect(() => {
inputRef.current?.focus();
}, [todos, tempTodo]);

return (
<header className="todoapp__header">
{!!todos.length && (
<button
type="button"
className={cn('todoapp__toggle-all', {
active: uncompletedTodosAmount === 0,
})}
data-cy="ToggleAllButton"
onClick={onToggleCompletedAll}
/>
)}

<InputForm
handleSubmit={handleSubmit}
inputRef={inputRef}
tempTodo={tempTodo}
inputValue={inputValue}
setInputValue={setInputValue}
/>
</header>
);
};
Loading
Loading