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

solution #1549

Open
wants to merge 6 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
204 changes: 184 additions & 20 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,190 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { TodoHeader } from './components/TodoHeader';
import { TodoFooter } from './components/TodoFooter';
import { ErrorNotification } from './components/ErrorNotification';
import { Todo } from './types/Todo';
import { addTodo, deleteTodo, getTodos, updateTodo } from './api/todos';
import { ErrorType } from './types/ErrorType';
import { FilterStatus } from './types/FilterStatus';
import { TodoList } from './components/TodoList';
import { USER_ID } from './constants/api';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorType>(ErrorType.Empty);
const [filterStatus, setFilterStatus] = useState<FilterStatus>(
FilterStatus.All,
);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

const inputAddRef = useRef<HTMLInputElement>(null);

const filteredTodos = useMemo(
() =>
todos.filter(todo => {
if (filterStatus === FilterStatus.All) {
return true;
}

return filterStatus === FilterStatus.Completed
? todo.completed
: !todo.completed;
}),
[todos, filterStatus],
);

const todosCompletedNum = useMemo(
() => todos.filter(todo => todo.completed).length,
[todos],
);

const areAllTodosCompleated = useMemo(
() => todos.every(todo => todo.completed),
[todos],
);

const todosActiveNum = useMemo(
() => todos.filter(todo => !todo.completed).length,
[todos],
);

const handleAddTodo = useCallback(
async (todoTitle: string) => {
setTempTodo({
id: 0,
title: todoTitle,
completed: false,
userId: USER_ID,
});
try {
const newTodo = await addTodo({ title: todoTitle, completed: false });

setTodos(prev => [...prev, newTodo]);
} catch (err) {
setErrorMessage(ErrorType.AddTodo);
inputAddRef?.current?.focus();
throw err;
} finally {
setTempTodo(null);
}
},
[setTempTodo, setTodos, setErrorMessage],
);

const handleRemoveTodo = useCallback(
async (todoId: number) => {
setLoadingTodoIds(prev => [...prev, todoId]);
try {
await deleteTodo(todoId);
setTodos(prev => prev.filter(todo => todo.id !== todoId));
} catch (err) {
setErrorMessage(ErrorType.DeleteTodo);
inputAddRef?.current?.focus();
throw err;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
}
},
[setLoadingTodoIds, setTodos, setErrorMessage],
);

const handleUpdateTodo = useCallback(
async (todoToUpdate: Todo) => {
setLoadingTodoIds(prev => [...prev, todoToUpdate.id]);
try {
const updatedTodo = await updateTodo(todoToUpdate);

setTodos(prev =>
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)),
);
} catch (err) {
setErrorMessage(ErrorType.UpdateTodo);
throw err;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
},
[setLoadingTodoIds, setTodos, setErrorMessage],
);

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

await Promise.all(completedTodos.map(todo => handleRemoveTodo(todo.id)));
}, [todos, handleRemoveTodo]);

const handleToggleAll = useCallback(async () => {
if (todosActiveNum > 0) {
const activeTodos = todos.filter(todo => !todo.completed);

await Promise.all(
activeTodos.map(todo => handleUpdateTodo({ ...todo, completed: true })),
);
} else {
await Promise.all(
todos.map(todo => handleUpdateTodo({ ...todo, completed: false })),
);
}
}, [todos, todosActiveNum, handleUpdateTodo]);

useEffect(() => {
const getAllTodos = async () => {
try {
const data = await getTodos();

setTodos(data);
} catch (err) {
setErrorMessage(ErrorType.LoadTodos);
}
};

getAllTodos();
}, []);

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">
<TodoHeader
handleAddTodo={handleAddTodo}
setErrorMessage={setErrorMessage}
isInputDisabled={!!tempTodo}
inputRef={inputAddRef}
handleToggleAll={handleToggleAll}
areAllTodosCompleated={areAllTodosCompleated}
todosLength={todos.length}
/>

{(!!todos.length || tempTodo) && (
<>
<TodoList
filteredTodos={filteredTodos}
handleRemoveTodo={handleRemoveTodo}
handleUpdateTodo={handleUpdateTodo}
loadingTodoIds={loadingTodoIds}
tempTodo={tempTodo}
/>

<TodoFooter
filterStatus={filterStatus}
setFilterStatus={setFilterStatus}
todosLeft={todosActiveNum}
todosCompleted={todosCompletedNum}
handleClearCompleted={handleClearCompleted}
/>
</>
)}
</div>

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

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

export const addTodo = (newTodo: Omit<Todo, 'id' | 'userId'>) => {
return client.post<Todo>(`${TODOS_API_PATH}`, {
...newTodo,
userId: USER_ID,
});
};

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

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

type Props = {
error: ErrorType;
setError: Dispatch<SetStateAction<ErrorType>>;
};

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

const timerId = setTimeout(() => {
setError(ErrorType.Empty);
}, 3000);

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

return (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: error === ErrorType.Empty,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(ErrorType.Empty)}
/>
{error}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorNotification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorNotification';
54 changes: 54 additions & 0 deletions src/components/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Dispatch, SetStateAction } from 'react';

import cn from 'classnames';
import { FilterStatus } from '../../types/FilterStatus';

type Props = {
filterStatus: FilterStatus;
setFilterStatus: Dispatch<SetStateAction<FilterStatus>>;
schyrva marked this conversation as resolved.
Show resolved Hide resolved
todosLeft: number;
todosCompleted: number;
handleClearCompleted: () => Promise<void>;
};

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

<nav className="filter" data-cy="Filter">
{Object.values(FilterStatus).map(filter => (
<a
key={filter}
href={`#/${filter !== FilterStatus.All && filter.toLowerCase()}`}
className={cn('filter__link', {
selected: filterStatus === filter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => setFilterStatus(filter)}
>
{filter}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={handleClearCompleted}
disabled={!todosCompleted}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/components/TodoFooter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoFooter';
Loading
Loading