diff --git a/README.md b/README.md index d3c3756ab9..4085f03414 100644 --- a/README.md +++ b/README.md @@ -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 `` with your Github username in the [DEMO LINK](https://.github.io/react_todo-app-with-api/) and add it to the PR description. +- Replace `` with your Github username in the [DEMO LINK](https://VasylPylypchynets.github.io/react_todo-app-with-api/) and add it to the PR description. diff --git a/src/App.tsx b/src/App.tsx index 81e011f432..933cab0d0e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,403 @@ -/* 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'; +import React, { + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import { + deleteTodo, + getTodos, + addTodo, + updateTodo, + USER_ID, +} from './api/todos'; +import { Todo } from './types/Todo'; +import { Header } from './components/Header/Header'; +import { TodoList } from './components/TodoList/TodoList'; +import { Footer } from './components/Footer/Footer'; +import { Error } from './components/ErrorMessage/ErrorMessage'; -const USER_ID = 0; +export enum SortBy { + All = 'all', + Active = 'active', + Completed = 'completed', +} export const App: React.FC = () => { - if (!USER_ID) { - return ; + const [todos, setTodos] = useState([]); + const [query, setQuery] = useState(''); + const [isLoadingChange, setIsLoadingChange] = useState(false); + const [isSubmiting, setIsSubmiting] = useState(false); + const [isUpdating, setIsUpdating] = useState(null); + + const [sortBy, setSortBy] = useState(SortBy.All); + const [errorMessage, setErrorMessage] = useState(null); + const [deleteTodoId, setDeleteTodoId] = useState(null); + const [cleanCompleted, setCleanCompleted] = useState(false); + const [newTask, setNewTask] = useState(''); + const [tempTodo, setTempTodo] = useState(null); + + const inputRef = useRef(null); + + useEffect(() => { + async function getTodosFromServer() { + try { + const todosFromServer = await getTodos(); + + setTodos(todosFromServer); + setErrorMessage(null); + } catch { + setErrorMessage('Unable to load todos'); + } + } + + getTodosFromServer(); + }, []); + + const itemsLeft = useMemo(() => { + return todos.filter(todo => !todo.completed).length; + }, [todos]); + + const handleFilter = useCallback( + (sort: SortBy, tasks: Todo[] = todos) => { + switch (sort) { + case SortBy.All: + return tasks; + case SortBy.Active: + return tasks.filter(todo => !todo.completed); + case SortBy.Completed: + return tasks.filter(todo => todo.completed); + } + }, + [todos], + ); + + const filteredTodos: Todo[] = useMemo( + () => handleFilter(sortBy, todos), + [sortBy, todos, handleFilter], + ); + + function handleUpdateTodoStatus(id: number) { + const todo = todos.find(currentTodo => currentTodo.id === id); + + if (!todo) { + return; + } + + const updatedStatus = { completed: !todo.completed }; + + if (updatedStatus) { + setIsUpdating([id]); + setErrorMessage(null); + + updateTodo(id, updatedStatus) + .then(() => { + setTodos(currentTodos => + currentTodos.map(item => + item.id === id + ? { ...item, completed: updatedStatus.completed } + : item, + ), + ); + }) + .catch(() => { + setErrorMessage('Unable to update a todo'); + }) + .finally(() => { + setIsUpdating(null); + }); + } + } + + function handleUpdateAllTodosStatus() { + const hasUncompleteTodo = todos.findIndex(todo => !todo.completed); + + if (hasUncompleteTodo >= 0) { + const updatedStatus = { completed: true }; + + const updateTodos = async () => { + const updatedTodos = todos.map(async todo => { + if (!todo.completed) { + setIsUpdating(prev => + prev === null ? [todo.id] : [...prev, todo.id], + ); + setErrorMessage(null); + + try { + await updateTodo(todo.id, updatedStatus); + + return { id: todo.id, status: 'fulfilled' }; + } catch { + setErrorMessage('Unable to update a todo'); + + return { id: todo.id, status: 'rejected' }; + } + } + + return { id: todo.id, status: 'skipped' }; + }); + + const results = await Promise.allSettled(updatedTodos); + + const successfulUpdated = results + .filter( + result => + result.status === 'fulfilled' && + result.value.status === 'fulfilled', + ) + .map( + result => + (result as PromiseFulfilledResult<{ id: number; status: string }>) + .value.id, + ); + + setTodos(currentTodos => + currentTodos.map(todo => + successfulUpdated.includes(todo.id) + ? { ...todo, completed: true } + : todo, + ), + ); + + setIsUpdating(null); + }; + + updateTodos(); + } + + if (hasUncompleteTodo < 0) { + const updatedStatus = { completed: false }; + + const updateTodos = async () => { + const updatedTodos = todos.map(async todo => { + setIsUpdating(prev => + prev === null ? [todo.id] : [...prev, todo.id], + ); + setErrorMessage(null); + + try { + await updateTodo(todo.id, updatedStatus); + + return { id: todo.id, status: 'fulfilled' }; + } catch { + setErrorMessage('Unable to update a todo'); + + return { id: todo.id, status: 'rejected' }; + } + }); + + const results = await Promise.allSettled(updatedTodos); + + const successfulUpdated = results + .filter( + result => + result.status === 'fulfilled' && + result.value.status === 'fulfilled', + ) + .map( + result => + (result as PromiseFulfilledResult<{ id: number; status: string }>) + .value.id, + ); + + setTodos(currentTodos => + currentTodos.map(todo => + successfulUpdated.includes(todo.id) + ? { ...todo, completed: false } + : todo, + ), + ); + + setIsUpdating(null); + }; + + updateTodos(); + } } + function handleSubmit(e: React.FormEvent) { + e.preventDefault(); + if (query.trim() !== '') { + setNewTask(query); + setIsSubmiting(true); + } else { + setErrorMessage('Title should not be empty'); + } + } + + function handleInput(e: React.ChangeEvent) { + setQuery(e.target.value); + } + + useEffect(() => { + if (tempTodo === null && inputRef.current) { + inputRef.current.focus(); + } + }, [tempTodo, todos.length]); + + useEffect(() => { + if (newTask.trim() !== '') { + const todo: Omit = { + userId: USER_ID, + title: newTask.trim(), + completed: false, + }; + + if (sortBy !== SortBy.Completed) { + setTempTodo({ id: 0, ...todo }); + } + + addTodo(todo) + .then(receivedTodo => { + setTempTodo(null); + setQuery(''); + setTodos(currentTodos => [...currentTodos, receivedTodo]); + }) + .catch(() => { + setErrorMessage('Unable to add a todo'); + }) + .finally(() => { + setTempTodo(null); + setIsSubmiting(false); + setNewTask(''); + }); + } else { + setIsSubmiting(false); + } + }, [newTask, sortBy]); + + useEffect(() => { + let timerEmpty: NodeJS.Timeout; + + if (errorMessage) { + timerEmpty = setTimeout(() => setErrorMessage(null), 3000); + } + + return () => clearTimeout(timerEmpty); + }, [errorMessage]); + + useEffect(() => { + async function deleteTodoFromServer() { + if (deleteTodoId !== null) { + setIsLoadingChange(true); + + try { + await deleteTodo(deleteTodoId).then(() => { + const newTodos = todos.filter(todo => todo.id !== deleteTodoId); + + setTodos(newTodos); + }); + } catch { + setErrorMessage('Unable to delete a todo'); + } finally { + setIsLoadingChange(false); + setDeleteTodoId(null); + } + } + } + + const cleanup = deleteTodoFromServer(); + + return () => { + if (cleanup instanceof Function) { + cleanup(); + } + }; + }, [deleteTodoId, todos]); + + useEffect(() => { + async function deleteTodoFromServer() { + if (cleanCompleted) { + setIsLoadingChange(true); + + const completedTodos = todos.filter(todo => todo.completed); + const deletionPromises = completedTodos.map(async todo => { + try { + await deleteTodo(todo.id); + + return { id: todo.id, status: 'fulfilled' }; + } catch (error) { + setErrorMessage('Unable to delete a todo'); + + return { id: todo.id, status: 'rejected' }; + } + }); + + const resolvedDeletions = await Promise.allSettled(deletionPromises); + + const successfulDeletions = resolvedDeletions + .filter( + date => + date.status === 'fulfilled' && date.value.status === 'fulfilled', + ) + .map( + date => + (date as PromiseFulfilledResult<{ id: number; status: string }>) + .value.id, + ); + + setTodos(prevTodos => + prevTodos.filter(todo => !successfulDeletions.includes(todo.id)), + ); + } + + setIsLoadingChange(false); + setCleanCompleted(false); + } + + deleteTodoFromServer(); + }, [cleanCompleted, todos]); + return ( -
-

- Copy all you need from the prev task: -
- - React Todo App - Add and Delete - -

- -

Styles are already copied

-
+
+

todos

+ +
+
+ + + + {/* Hide the footer if there are no todos */} + {todos.length !== 0 && ( +
+ )} +
+ + {/* DON'T use conditional rendering to hide the notification */} + {/* Add the 'hidden' class to hide the message smoothly */} + + +
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..863198838e --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,23 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 2085; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const deleteTodo = (TODO_ID: number) => { + return client.delete(`/todos/${TODO_ID}`); +}; + +export const addTodo = (todo: Omit) => { + return client.post(`/todos`, todo); +}; + +export const updateTodo = ( + TODO_ID: number, + updatedTodo: Pick | Pick, +) => { + return client.patch(`/todos/${TODO_ID}`, updatedTodo); +}; diff --git a/src/components/ErrorMessage/ErrorMessage.tsx b/src/components/ErrorMessage/ErrorMessage.tsx new file mode 100644 index 0000000000..6e4bd5a034 --- /dev/null +++ b/src/components/ErrorMessage/ErrorMessage.tsx @@ -0,0 +1,32 @@ +import classNames from 'classnames'; + +type ErrorProps = { + errorMessage: string | boolean | null; + onErrorMessage: React.Dispatch>; +}; + +export function Error({ errorMessage, onErrorMessage }: ErrorProps) { + return ( +
+
+ ); +} diff --git a/src/components/Footer/Footer.tsx b/src/components/Footer/Footer.tsx new file mode 100644 index 0000000000..b91fec0053 --- /dev/null +++ b/src/components/Footer/Footer.tsx @@ -0,0 +1,53 @@ +import classNames from 'classnames'; +import { SortBy } from '../../App'; + +type FooterProps = { + itemsLeft: number; + sortBy: string; + onSortBy: (sort: SortBy) => void; + onCleanCompleted: (clean: boolean) => void; + todosLength: number; +}; + +export function Footer({ + itemsLeft, + sortBy, + onSortBy, + onCleanCompleted, + todosLength, +}: FooterProps) { + return ( + + ); +} diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx new file mode 100644 index 0000000000..8704ee6617 --- /dev/null +++ b/src/components/Header/Header.tsx @@ -0,0 +1,53 @@ +import classNames from 'classnames'; + +type HeaderProps = { + query: string; + onInput: (e: React.ChangeEvent) => void; + onSubmit: (e: React.FormEvent) => void; + isSubmiting: boolean; + inputRef: React.RefObject; + onUpdateAllTodos: () => void; + itemsLeft: number; + todosLength: number; +}; + +export function Header({ + query, + onInput, + onSubmit, + isSubmiting, + inputRef, + onUpdateAllTodos, + itemsLeft, + todosLength, +}: HeaderProps) { + return ( +
+ {/* this button should have `active` class only if all todos are completed */} + {todosLength > 0 && ( +
+ ); +} diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx new file mode 100644 index 0000000000..2ad33979d2 --- /dev/null +++ b/src/components/TodoItem/TodoItem.tsx @@ -0,0 +1,181 @@ +import classNames from 'classnames'; + +import { useEffect, useRef, useState } from 'react'; +import { Todo } from '../../types/Todo'; +import { updateTodo } from '../../api/todos'; + +type TodoItemProps = { + onDeleteTodo: (id: number) => void; + todo: Todo; + isLoadingChange: boolean; + deleteTodoId: number | null; + cleanCompleted: boolean; + isAdding?: boolean; + onUpdateTodo: (id: number) => void; + isUpdating?: number[] | null; + setIsUpdating: React.Dispatch>; + setErrorMessage: React.Dispatch>; + setTodos: React.Dispatch>; + setDeleteTodoId: React.Dispatch>; +}; + +export function TodoItem({ + todo, + onDeleteTodo, + isLoadingChange, + deleteTodoId, + cleanCompleted, + isAdding, + onUpdateTodo, + isUpdating, + setIsUpdating, + setErrorMessage, + setTodos, + setDeleteTodoId, +}: TodoItemProps) { + const [itemEditingId, setItemEditingId] = useState(null); + const [newTitle, setNewTitle] = useState(''); + + const inputRef = useRef(null); + + function handleUpadateNewTitle(id: number, title: string) { + if (todo?.title === title) { + setItemEditingId(null); + + return; + } + + if (title.trim() === '') { + setDeleteTodoId(id); + setIsUpdating([id]); + + return; + } + + if (title) { + if (!isUpdating) { + setIsUpdating([id]); + } + + setErrorMessage(null); + + const updatedTitle = { title: title.trim() }; + + updateTodo(id, updatedTitle) + .then(() => { + setTodos(currentTodos => + currentTodos.map(item => + item.id === id ? { ...item, title: updatedTitle.title } : item, + ), + ); + + setItemEditingId(null); + }) + .catch(() => { + setErrorMessage('Unable to update a todo'); + setItemEditingId(id); + setNewTitle(title); + inputRef.current?.focus(); + }) + .finally(() => { + setIsUpdating(null); + }); + } + } + + function handleCancel(e: React.KeyboardEvent) { + if (e.key === 'Escape') { + setItemEditingId(null); + setNewTitle(todo.title); + } + } + + useEffect(() => { + if (itemEditingId === todo.id && inputRef.current) { + inputRef.current.focus(); + setNewTitle(todo.title); + } + }, [itemEditingId, todo.id, todo.title]); + + return ( +
+ + + {itemEditingId !== todo.id && ( + <> + setItemEditingId(todo.id)} + > + {todo.title} + + {/* Remove button appears only on hover */} + + + )} + + {/* This todo is being edited */} + + {/* This form is shown instead of the title and remove button */} + {itemEditingId === todo.id && ( +
{ + e.preventDefault(); + handleUpadateNewTitle(todo.id, newTitle); + }} + > + setNewTitle(e.target.value)} + onBlur={() => { + handleUpadateNewTitle(todo.id, newTitle); + }} + onKeyUp={handleCancel} + /> +
+ )} + + {/* Overlay will cover the todo while it is being deleted or updated */} +
+
+
+
+
+ ); +} diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx new file mode 100644 index 0000000000..15c0dea151 --- /dev/null +++ b/src/components/TodoList/TodoList.tsx @@ -0,0 +1,70 @@ +import { Todo } from '../../types/Todo'; +import { TodoItem } from '../TodoItem/TodoItem'; + +type TodoListProps = { + onDeleteTodo: (id: number) => void; + todos: Todo[]; + isLoadingChange: boolean; + deleteTodoId: number | null; + cleanCompleted: boolean; + tempTodo: Todo | null; + onUpdateTodo: (id: number) => void; + isUpdating: number[] | null; + setIsUpdating: React.Dispatch>; + setErrorMessage: React.Dispatch>; + setTodos: React.Dispatch>; + setDeleteTodoId: React.Dispatch>; +}; + +export function TodoList({ + onDeleteTodo, + todos, + isLoadingChange, + deleteTodoId, + cleanCompleted, + tempTodo, + onUpdateTodo, + isUpdating, + setIsUpdating, + setErrorMessage, + setTodos, + setDeleteTodoId, +}: TodoListProps) { + return ( +
+ {todos.map(todo => ( + + ))} + + {tempTodo && ( + + )} +
+ ); +} diff --git a/src/types/Todo.ts b/src/types/Todo.ts new file mode 100644 index 0000000000..3f52a5fdde --- /dev/null +++ b/src/types/Todo.ts @@ -0,0 +1,6 @@ +export interface Todo { + id: number; + userId: number; + title: string; + completed: boolean; +} diff --git a/src/utils/fetchClient.ts b/src/utils/fetchClient.ts new file mode 100644 index 0000000000..708ac4c17b --- /dev/null +++ b/src/utils/fetchClient.ts @@ -0,0 +1,46 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +const BASE_URL = 'https://mate.academy/students-api'; + +// returns a promise resolved after a given delay +function wait(delay: number) { + return new Promise(resolve => { + setTimeout(resolve, delay); + }); +} + +// To have autocompletion and avoid mistypes +type RequestMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'; + +function request( + url: string, + method: RequestMethod = 'GET', + data: any = null, // we can send any data to the server +): Promise { + const options: RequestInit = { method }; + + if (data) { + // We add body and Content-Type only for the requests with data + options.body = JSON.stringify(data); + options.headers = { + 'Content-Type': 'application/json; charset=UTF-8', + }; + } + + // DON'T change the delay it is required for tests + return wait(100) + .then(() => fetch(BASE_URL + url, options)) + .then(response => { + if (!response.ok) { + throw new Error(); + } + + return response.json(); + }); +} + +export const client = { + get: (url: string) => request(url), + post: (url: string, data: any) => request(url, 'POST', data), + patch: (url: string, data: any) => request(url, 'PATCH', data), + delete: (url: string) => request(url, 'DELETE'), +};