diff --git a/README.md b/README.md index 47a1add059..5fc4f26ec4 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://maxsabo.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..8c336a3638 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,26 +1,177 @@ -/* 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'; - -const USER_ID = 0; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { + addTodo, + deleteTodo, + getTodos, + updateTodo, + USER_ID, +} from './api/todos'; +import { Todo } from './types/Todo'; +import { TodoHeader } from './components/TodoHeader'; +import { TodoFooter } from './components/TodoFooter'; +import { ErrorNotification } from './components/ErrorNotification'; +import { ErrorType } from './types/ErrorTypes'; +import { FilterStatus } from './types/FilterStatus'; +import { TodoList } from './components/TodoList'; export const App: React.FC = () => { - if (!USER_ID) { - return ; - } + const [todos, setTodos] = useState([]); + const [errorMessage, setErrorMessage] = useState(ErrorType.Empty); + const [filterStatus, setFilterStatus] = useState( + FilterStatus.All, + ); + const [tempTodo, setTempTodo] = useState(null); + const [loadingTodoIds, setLoadingTodoIds] = useState([]); + + const inputAddRef = useRef(null); + + const filteredTodos = useMemo( + () => + todos.filter(todo => { + if (filterStatus === FilterStatus.All) { + return true; + } + + return filterStatus === FilterStatus.Completed + ? todo.completed + : !todo.completed; + }), + [todos, filterStatus], + ); + + const todosActiveNum = useMemo( + () => todos.filter(todo => !todo.completed).length, + [todos], + ); + + const todosCompleted = useMemo( + () => todos.filter(todo => todo.completed).length, + [todos], + ); + + const areAllTodosCompleted = useMemo( + () => todos.every(todo => todo.completed), + [todos], + ); + + const onAddTodo = 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); + } + }; + + const onRemoveTodo = 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)); + } + }; + + const onUpdateTodo = 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)); + } + }; + + const onClearCompleted = async () => { + const completedTodos = todos.filter(todo => todo.completed); + + completedTodos.forEach(todo => { + onRemoveTodo(todo.id); + }); + }; + + const onToggleAll = async () => { + if (todosActiveNum > 0) { + const activeTodos = todos.filter(todo => !todo.completed); + + activeTodos.forEach(todo => { + onUpdateTodo({ ...todo, completed: true }); + }); + } else { + todos.forEach(todo => { + onUpdateTodo({ ...todo, completed: false }); + }); + } + }; + + useEffect(() => { + (async () => { + try { + const data = await getTodos(); + + setTodos(data); + } catch (err) { + setErrorMessage(ErrorType.LoadTodos); + } + })(); + }, []); return ( -
-

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

- -

Styles are already copied

-
+
+

todos

+ +
+ + + {(todos.length > 0 || tempTodo) && ( + <> + + + + )} +
+ + +
); }; diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..b519829a76 --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,20 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const USER_ID = 2164; + +export const getTodos = () => { + return client.get(`/todos?userId=${USER_ID}`); +}; + +export const addTodo = (newTodo: Omit) => { + return client.post(`/todos`, { ...newTodo, userId: USER_ID }); +}; + +export const deleteTodo = (todoId: number) => { + return client.delete(`/todos/${todoId}`); +}; + +export const updateTodo = (todo: Todo) => { + return client.patch(`/todos/${todo.id}`, todo); +}; diff --git a/src/components/ErrorNotification.tsx b/src/components/ErrorNotification.tsx new file mode 100644 index 0000000000..3c5dc467aa --- /dev/null +++ b/src/components/ErrorNotification.tsx @@ -0,0 +1,44 @@ +import React, { Dispatch, SetStateAction, useEffect } from 'react'; +import { ErrorType } from '../types/ErrorTypes'; +import classNames from 'classnames'; + +type Props = { + error: ErrorType; + setError: Dispatch>; +}; + +export const ErrorNotification: React.FC = props => { + const { error, setError } = props; + + useEffect(() => { + if (error === ErrorType.Empty) { + return; + } + + const timerId = setTimeout(() => { + setError(ErrorType.Empty); + }, 3000); + + return () => { + clearTimeout(timerId); + }; + }, [error, setError]); + + return ( +
+
+ ); +}; diff --git a/src/components/TodoFooter.tsx b/src/components/TodoFooter.tsx new file mode 100644 index 0000000000..045ac864b3 --- /dev/null +++ b/src/components/TodoFooter.tsx @@ -0,0 +1,57 @@ +import React, { Dispatch, SetStateAction } from 'react'; +import { FilterStatus } from '../types/FilterStatus'; +import classNames from 'classnames'; + +type Props = { + filterStatus: FilterStatus; + setFilterStatus: Dispatch>; + todosLeft: number; + todosCompleted: number; + onClearCompleted: () => Promise; +}; + +export const TodoFooter: React.FC = props => { + const { + filterStatus, + setFilterStatus, + todosLeft, + todosCompleted, + onClearCompleted, + } = props; + + return ( +
+ + {todosLeft} items left + + + {/* Active link should have the 'selected' class */} + + + {/* this button should be disabled if there are no completed todos */} + +
+ ); +}; diff --git a/src/components/TodoHeader.tsx b/src/components/TodoHeader.tsx new file mode 100644 index 0000000000..d669209bb7 --- /dev/null +++ b/src/components/TodoHeader.tsx @@ -0,0 +1,80 @@ +import React, { Dispatch, SetStateAction, useEffect, useState } from 'react'; +import { ErrorType } from '../types/ErrorTypes'; +import classNames from 'classnames'; + +type Props = { + onAddTodo: (value: string) => Promise; + setErrorMessage: Dispatch>; + isInputDisabled: boolean; + todosLength: number; + areAllTodosCompleted: boolean; + onToggleAll: () => Promise; + inputRef: React.RefObject | null; +}; + +export const TodoHeader: React.FC = props => { + const { + onAddTodo, + setErrorMessage, + isInputDisabled, + onToggleAll, + todosLength, + areAllTodosCompleted, + inputRef, + } = props; + + const [inputValue, setInputValue] = useState(''); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + if (inputValue.trim() === '') { + setErrorMessage(ErrorType.EmptyTitle); + + return; + } + + try { + await onAddTodo(inputValue.trim()); + setInputValue(''); + } catch (err) {} + }; + + useEffect(() => { + inputRef?.current?.focus(); + }, [todosLength, inputRef]); + + useEffect(() => { + if (!isInputDisabled) { + inputRef?.current?.focus(); + } + }, [isInputDisabled, inputRef]); + + return ( +
+ {todosLength !== 0 && ( +
+ ); +}; diff --git a/src/components/TodoItem.tsx b/src/components/TodoItem.tsx new file mode 100644 index 0000000000..a06ed6ddde --- /dev/null +++ b/src/components/TodoItem.tsx @@ -0,0 +1,129 @@ +/* eslint-disable jsx-a11y/label-has-associated-control */ +import React, { Dispatch, SetStateAction, useRef, useState } from 'react'; +import { Todo } from '../types/Todo'; +import classNames from 'classnames'; + +type Props = { + todo: Todo; + isLoading?: boolean; + isInEditMode?: boolean; + onRemoveTodo: (todoId: number) => Promise; + onUpdateTodo: (todo: Todo) => Promise; + setEditedTodoId: Dispatch>; +}; + +export const TodoItem: React.FC = props => { + const { + todo, + isLoading, + isInEditMode, + onRemoveTodo, + onUpdateTodo, + setEditedTodoId, + } = props; + + const [todoTitleValue, setTodoTitleValue] = useState(todo.title); + + const inputRef = useRef(null); + + const onCheckTodo = () => { + const todoToUpdate = { ...todo, completed: !todo.completed }; + + onUpdateTodo(todoToUpdate); + }; + + const onDoubleClick = () => { + setEditedTodoId(todo.id); + }; + + // eslint-disable-next-line max-len, prettier/prettier + const onBlur = async (event: React.FocusEvent | React.FormEvent, + ) => { + event.preventDefault(); + const normalizedTitle = todoTitleValue.trim(); + + if (todo.title === normalizedTitle) { + setEditedTodoId(null); + + return; + } + + try { + if (normalizedTitle === '') { + await onRemoveTodo(todo.id); + } else { + await onUpdateTodo({ ...todo, title: normalizedTitle }); + } + + setEditedTodoId(null); + } catch (err) { + inputRef?.current?.focus(); + } + }; + + const onKeyUp = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setEditedTodoId(null); + setTodoTitleValue(todo.title); + } + }; + + return ( +
+ + + {isInEditMode ? ( +
+ setTodoTitleValue(e.target.value)} + onKeyUp={onKeyUp} + ref={inputRef} + /> +
+ ) : ( + <> + + {todo.title} + + + + )} + +
+
+
+
+
+ ); +}; diff --git a/src/components/TodoList.tsx b/src/components/TodoList.tsx new file mode 100644 index 0000000000..0a7f40578e --- /dev/null +++ b/src/components/TodoList.tsx @@ -0,0 +1,48 @@ +import React, { useState } from 'react'; +import { TodoItem } from './TodoItem'; +import { Todo } from '../types/Todo'; + +type Props = { + filteredTodos: Todo[]; + loadingTodoIds: number[]; + tempTodo: Todo | null; + onRemoveTodo: (todoId: number) => Promise; + onUpdateTodo: (todo: Todo) => Promise; +}; + +export const TodoList: React.FC = props => { + const { + filteredTodos, + loadingTodoIds, + tempTodo, + onRemoveTodo, + onUpdateTodo, + } = props; + + const [editedTodoId, setEditedTodoId] = useState(null); + + return ( +
+ {filteredTodos.map(todo => ( + + ))} + {tempTodo && ( + + )} +
+ ); +}; diff --git a/src/types/ErrorTypes.ts b/src/types/ErrorTypes.ts new file mode 100644 index 0000000000..66f0a8d5ad --- /dev/null +++ b/src/types/ErrorTypes.ts @@ -0,0 +1,8 @@ +export enum ErrorType { + Empty = '', + LoadTodos = 'Unable to load todos', + EmptyTitle = 'Title should not be empty', + AddTodo = 'Unable to add a todo', + DeleteTodo = 'Unable to delete a todo', + UpdateTodo = 'Unable to update a todo', +} diff --git a/src/types/FilterStatus.ts b/src/types/FilterStatus.ts new file mode 100644 index 0000000000..7ca17f289b --- /dev/null +++ b/src/types/FilterStatus.ts @@ -0,0 +1,5 @@ +export enum FilterStatus { + All = 'All', + Active = 'Active', + Completed = 'Completed', +} 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'), +};