From aabb460609b5e2e64f2664d4eda0202025c2543f Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Wed, 27 Sep 2023 09:14:09 +0300 Subject: [PATCH 1/7] first version of TodoApp, not all tests are completed --- README.md | 2 +- src/App.tsx | 267 +++++++++++++++++- src/UserWarning.tsx | 2 +- src/api/todos.ts | 14 + src/components/TodoError/TodoError.tsx | 34 +++ src/components/TodoFilter/TodoFilter.tsx | 49 ++++ src/components/TodoItem/TodoItem.tsx | 142 ++++++++++ src/components/TodoList/TodoList.tsx | 38 +++ .../TodoLoadingItem/TodoLoadingItem.tsx | 47 +++ src/styles/todo.scss | 63 +---- src/styles/todoapp.scss | 5 - src/types/Error.ts | 9 + src/types/Status.ts | 5 + src/types/Todo.ts | 6 + src/utils/fetchClient.ts | 46 +++ src/utils/functions.ts | 42 +++ 16 files changed, 697 insertions(+), 74 deletions(-) create mode 100644 src/api/todos.ts create mode 100644 src/components/TodoError/TodoError.tsx create mode 100644 src/components/TodoFilter/TodoFilter.tsx create mode 100644 src/components/TodoItem/TodoItem.tsx create mode 100644 src/components/TodoList/TodoList.tsx create mode 100644 src/components/TodoLoadingItem/TodoLoadingItem.tsx create mode 100644 src/types/Error.ts create mode 100644 src/types/Status.ts create mode 100644 src/types/Todo.ts create mode 100644 src/utils/fetchClient.ts create mode 100644 src/utils/functions.ts diff --git a/README.md b/README.md index af7dae81f6..2c85824161 100644 --- a/README.md +++ b/README.md @@ -41,4 +41,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://viktoria-roik.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 5749bdf784..1c8175443c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,24 +1,267 @@ -/* eslint-disable max-len */ /* eslint-disable jsx-a11y/control-has-associated-label */ -import React from 'react'; +import React, { useEffect, useRef, useState } from 'react'; +import classNames from 'classnames'; +import { Todo } from './types/Todo'; +import { Status } from './types/Status'; +import { Error } from './types/Error'; +import { + getTodos, + deleteTodo, + createTodo, +} from './api/todos'; +import { TodoList } from './components/TodoList/TodoList'; +import { TodoFilter } from './components/TodoFilter/TodoFilter'; import { UserWarning } from './UserWarning'; +import { TodoError } from './components/TodoError/TodoError'; +import { TodoLoadingItem } from './components/TodoLoadingItem/TodoLoadingItem'; +import { filterTodos, getItemsLeftCountMessage } from './utils/functions'; +import { client } from './utils/fetchClient'; -const USER_ID = 0; +const USER_ID = 11521; export const App: React.FC = () => { + const [todos, setTodos] = useState([]); + const [status, setStatus] = useState(Status.All); + const [errorMessage, setErrorMessage] = useState(Error.None); + const [value, setValue] = useState(''); + const [isSubmitted, setIsSubmitted] = useState(false); + const [tempTodo, setTempTodo] = useState(null); + const [processingIds, setProcessingIds] = useState([]); + const [areSubmiting, setAreSubmiting] = useState(false); + const [togglingId, setTogglingId] = useState(null); + const [wasEdited, setWasEdited] = useState(false); + + const inputRef = useRef(null); + + useEffect(() => { + getTodos(USER_ID) + .then(setTodos) + .catch(() => setErrorMessage(Error.Load)); + }, []); + + useEffect(() => { + if (errorMessage) { + setTimeout(() => { + setErrorMessage(Error.None); + }, 3000); + } + }, [errorMessage]); + + useEffect(() => { + if (wasEdited) { + inputRef.current?.focus(); + } + }, [wasEdited]); + + const visibleTodos = filterTodos(todos, status); + + const activeTodosCount = todos.filter(todo => !todo.completed); + const completedTodosCount = todos.filter(todo => todo.completed); + + function addTodo({ userId, title, completed }: Todo): Promise { + setErrorMessage(Error.None); + setWasEdited(false); + + return createTodo({ userId, title, completed }) + .then(newTodo => { + setTodos(currentTodos => [...currentTodos, newTodo]); + }) + .catch(() => { + setErrorMessage(Error.Add); + }) + .finally(() => { + setWasEdited(true); + }); + } + + const handleSubmit = (event: React.ChangeEvent) => { + event.preventDefault(); + setIsSubmitted(true); + + const todoTitle = value.trim(); + + const newTodo = { + id: todos.length + 1, + title: todoTitle, + completed: false, + userId: USER_ID, + }; + + if (!todoTitle) { + setErrorMessage(Error.EmptyTitle); + setIsSubmitted(false); + } else { + addTodo(newTodo) + .then(() => { + setValue(''); + }) + .finally(() => { + setTempTodo(null); + setIsSubmitted(false); + }); + } + }; + + const onDelete = (todoId: number) => { + setProcessingIds((prevIds) => [...prevIds, todoId]); + deleteTodo(todoId) + .then(() => setTodos( + currentTodos => currentTodos.filter( + todo => todo.id !== todoId, + ), + )) + .catch(() => setErrorMessage(Error.Delete)) + .finally(() => setProcessingIds( + (prevIds) => prevIds.filter(id => id !== todoId), + )); + }; + + const onDeleteCompleted = () => { + const allCompletedTodos = todos.filter(todo => todo.completed); + + allCompletedTodos.forEach((todo) => { + onDelete(todo.id); + }); + }; + + const onToggle = (todoId: number) => { + const todoToToggle = todos.find((todo) => todo.id === todoId); + + setIsSubmitted(true); + setTogglingId(todoId); + + if (!todoToToggle) { + return; + } + + client + .patch(`/todos/${todoId}`, { completed: !todoToToggle.completed }) + .catch(() => setErrorMessage(Error.Toggle)) + .finally(() => { + setTogglingId(null); + setIsSubmitted(false); + }); + }; + + const toggleAll = () => { + const allTodosAreCompleted = todos.length === completedTodosCount.length; + + const promiseArray = ( + allTodosAreCompleted + ? completedTodosCount + : activeTodosCount).map((todo: { id: number; completed: boolean; }) => client.patch(`/todos/${todo.id}`, { completed: !todo.completed })); + + setAreSubmiting(true); + + Promise.all(promiseArray) + .then(() => { + setTodos(todos.map(todo => ( + { ...todo, completed: !allTodosAreCompleted } + ))); + }) + .catch(() => setErrorMessage(Error.Toggle)) + .finally(() => setAreSubmiting(false)); + }; + + const updateTodos = (todoId: number, data: Todo) => { + return client + .patch(`/todos/${todoId}`, data) + .then(receivedTodo => { + setTodos(todos.map(todo => (todo.id === todoId ? receivedTodo : todo))); + }) + .catch(() => setErrorMessage(Error.Update)) + .finally(() => { + setTogglingId(null); + setIsSubmitted(false); + }); + }; + if (!USER_ID) { return ; } return ( -
-

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

- -

Styles are already copied

-
+
+

todos

+ +
+
+ {todos.length !== 0 && ( +
+ + {!!todos.length && ( + <> + + + {tempTodo && ( + + )} +
+ + {getItemsLeftCountMessage(activeTodosCount)} + + + +
+ + )} + +
+ + { + setErrorMessage(Error.None); + }} + /> +
); }; diff --git a/src/UserWarning.tsx b/src/UserWarning.tsx index db7dd16e32..e66095a30b 100644 --- a/src/UserWarning.tsx +++ b/src/UserWarning.tsx @@ -13,7 +13,7 @@ export const UserWarning: React.FC = () => ( {' '} and save it in the app {' '} -
const USER_ID = ...
+
const USER_ID = 11521
All requests to the API must be sent with this userId. diff --git a/src/api/todos.ts b/src/api/todos.ts new file mode 100644 index 0000000000..3d7651aada --- /dev/null +++ b/src/api/todos.ts @@ -0,0 +1,14 @@ +import { Todo } from '../types/Todo'; +import { client } from '../utils/fetchClient'; + +export const getTodos = (userId: number) => { + return client.get(`/todos?userId=${userId}`); +}; + +export const createTodo = ({ title, completed, userId }: Omit) => { + return client.post('/todos', { title, completed, userId }); +}; + +export const deleteTodo = (todoId: number) => { + return client.delete(`/todos/${todoId}`); +}; diff --git a/src/components/TodoError/TodoError.tsx b/src/components/TodoError/TodoError.tsx new file mode 100644 index 0000000000..c0e95627d6 --- /dev/null +++ b/src/components/TodoError/TodoError.tsx @@ -0,0 +1,34 @@ +/* eslint-disable jsx-a11y/control-has-associated-label */ +import React from 'react'; +import classNames from 'classnames'; +import { Error } from '../../types/Error'; + +type Props = { + errorMessage: Error, + onErrorChange: () => void +}; + +export const TodoError: React.FC = ({ errorMessage, onErrorChange }) => { + return ( +
+
+ ); +}; diff --git a/src/components/TodoFilter/TodoFilter.tsx b/src/components/TodoFilter/TodoFilter.tsx new file mode 100644 index 0000000000..125139caba --- /dev/null +++ b/src/components/TodoFilter/TodoFilter.tsx @@ -0,0 +1,49 @@ +import classNames from 'classnames'; +import { Status } from '../../types/Status'; + +type Props = { + handleFilterStatus: (status: Status) => void, + todosFilterStatus: Status +}; + +export const TodoFilter: React.FC = ({ + handleFilterStatus, + todosFilterStatus, +}) => { + return ( + + ); +}; diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx new file mode 100644 index 0000000000..606053523d --- /dev/null +++ b/src/components/TodoItem/TodoItem.tsx @@ -0,0 +1,142 @@ +import React, { useEffect, useRef, useState } from 'react'; +import classNames from 'classnames'; +import { Todo } from '../../types/Todo'; +import { client } from '../../utils/fetchClient'; + +type Props = { + todo: Todo, + processingIds: number[], + onDelete: (id: number) => void, + onToggle: (todoId: number) => void, + togglingId: number | null, + onUpdate: (todoId: number, data: Todo) => void, + areSubmiting: boolean, +}; + +export const TodoItem: React.FC = ({ + todo, + processingIds, + onDelete, + onToggle, + togglingId, + onUpdate, + areSubmiting, +}) => { + const [isEditing, setIsEditing] = useState(false); + const [newTodoTitle, setNewTodoTitle] = useState(todo.title); + + const inputRef = useRef(null); + + useEffect(() => { + if (isEditing) { + inputRef.current?.focus(); + } + }, [isEditing]); + + const handleTodoTitleChange = () => { + setIsEditing(true); + }; + + const handleFormSubmit = (event: React.FormEvent) => { + event.preventDefault(); + + const currentTodoTitle = todo.title; + + if (newTodoTitle === currentTodoTitle) { + setIsEditing(false); + } else if (newTodoTitle.trim() === '') { + onDelete(todo.id); + } else { + setIsEditing(true); + client + .patch(`/todos/${todo.id}`, { title: newTodoTitle }) + .then(() => { + setIsEditing(false); + onUpdate(todo.id, { ...todo, title: newTodoTitle }); + }) + .catch(() => { + setIsEditing(false); + onUpdate(todo.id, todo); + }); + } + }; + + const handleKeyUp = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setIsEditing(false); + } + }; + + return ( +
+ + + {isEditing ? ( +
+ setNewTodoTitle(event.target.value)} + onBlur={handleFormSubmit} + onKeyUp={handleKeyUp} + // eslint-disable-next-line jsx-a11y/no-autofocus + autoFocus + /> +
+ ) : ( + + {todo.title} + + )} + + + +
+
+
+
+
+ ); +}; diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx new file mode 100644 index 0000000000..652608a294 --- /dev/null +++ b/src/components/TodoList/TodoList.tsx @@ -0,0 +1,38 @@ +import { TodoItem } from '../TodoItem/TodoItem'; +import { Todo } from '../../types/Todo'; + +type Props = { + todos: Todo[], + onDelete: (todoId: number) => void, + processingIds: number[], + onToggle: (todoId: number) => void, + togglingId: number | null, + onUpdate: (todoId: number, data: Todo) => void, + isSubmitted: boolean, + areSubmiting: boolean, +}; + +export const TodoList: React.FC = ({ + todos, + onDelete, + processingIds, + onToggle, + togglingId, + onUpdate, + areSubmiting, +}) => ( +
+ {todos.map((todo) => ( + + ))} +
+); diff --git a/src/components/TodoLoadingItem/TodoLoadingItem.tsx b/src/components/TodoLoadingItem/TodoLoadingItem.tsx new file mode 100644 index 0000000000..b4ff9c4841 --- /dev/null +++ b/src/components/TodoLoadingItem/TodoLoadingItem.tsx @@ -0,0 +1,47 @@ +import className from 'classnames'; +import { Todo } from '../../types/Todo'; + +type Props = { + tempTodo: Todo | null, + isSubmitted: boolean, +}; + +export const TodoLoadingItem: React.FC = ({ tempTodo, isSubmitted }) => { + return ( + <> +
+ + + {tempTodo?.title} + + + {/* */} + +
+
+
+
+
+ + ); +}; diff --git a/src/styles/todo.scss b/src/styles/todo.scss index c7f93ff6b9..fc99714ef2 100644 --- a/src/styles/todo.scss +++ b/src/styles/todo.scss @@ -8,7 +8,7 @@ font-size: 24px; line-height: 1.4em; border-bottom: 1px solid #ededed; - + &:last-child { border-bottom: 0; } @@ -30,7 +30,7 @@ &__title { padding: 12px 15px; - + word-break: break-all; transition: color 0.4s; } @@ -56,7 +56,7 @@ border: 0; background: none; cursor: pointer; - + transform: translateY(-2px); opacity: 0; transition: color 0.2s ease-out; @@ -65,7 +65,7 @@ color: #af5b5e; } } - + &:hover &__remove { opacity: 1; } @@ -73,13 +73,13 @@ &__title-field { width: 100%; padding: 11px 14px; - + font-size: inherit; line-height: inherit; font-family: inherit; font-weight: inherit; color: inherit; - + border: 1px solid #999; box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); @@ -92,58 +92,11 @@ .overlay { position: absolute; - top: 0; left: 0; right: 0; - height: 58px; + bottom: 0; + top: 0; opacity: 0.5; } } - -.item-enter { - max-height: 0; -} - -.item-enter-active { - overflow: hidden; - max-height: 58px; - transition: max-height 0.3s ease-in-out; -} - -.item-exit { - max-height: 58px; -} - -.item-exit-active { - overflow: hidden; - max-height: 0; - transition: max-height 0.3s ease-in-out; -} - -.temp-item-enter { - max-height: 0; -} - -.temp-item-enter-active { - overflow: hidden; - max-height: 58px; - transition: max-height 0.3s ease-in-out; -} - -.temp-item-exit { - max-height: 58px; -} - -.temp-item-exit-active { - transform: translateY(-58px); - max-height: 0; - opacity: 0; - transition: 0.3s ease-in-out; - transition-property: opacity, max-height, transform; -} - -.has-error .temp-item-exit-active { - transform: translateY(0); - overflow: hidden; -} diff --git a/src/styles/todoapp.scss b/src/styles/todoapp.scss index 9095f1847f..836166156b 100644 --- a/src/styles/todoapp.scss +++ b/src/styles/todoapp.scss @@ -121,7 +121,6 @@ appearance: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; - transition: opacity 0.3s; &:hover { text-decoration: underline; @@ -130,9 +129,5 @@ &:active { text-decoration: none; } - - &:disabled { - visibility: hidden; - } } } diff --git a/src/types/Error.ts b/src/types/Error.ts new file mode 100644 index 0000000000..a5b57b64ee --- /dev/null +++ b/src/types/Error.ts @@ -0,0 +1,9 @@ +export enum Error { + None = '', + Load = 'Unable to load todos', + Add = 'Unable to add a todo', + Delete = 'Unable to delete a todo', + Update = 'Unable to update a todo', + EmptyTitle = 'Title should not be empty', + Toggle = 'Unable to toggle todos', +} diff --git a/src/types/Status.ts b/src/types/Status.ts new file mode 100644 index 0000000000..dc864cc93b --- /dev/null +++ b/src/types/Status.ts @@ -0,0 +1,5 @@ +export enum Status { + 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..42421feae0 --- /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', + }; + } + + // we wait for testing purpose to see loaders + return wait(300) + .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'), +}; diff --git a/src/utils/functions.ts b/src/utils/functions.ts new file mode 100644 index 0000000000..73afcd5276 --- /dev/null +++ b/src/utils/functions.ts @@ -0,0 +1,42 @@ +import { Status } from '../types/Status'; +import { Todo } from '../types/Todo'; + +export const filterTodos = (todos: Todo[], filterStatus: Status): Todo[] => { + let filteredTodos: Todo[] = []; + + switch (filterStatus) { + case Status.All: { + filteredTodos = todos; + break; + } + + case Status.Active: { + filteredTodos = todos.filter(todo => todo.completed === false); + + break; + } + + case Status.Completed: { + filteredTodos = todos.filter(todo => todo.completed === true); + + break; + } + + default: filteredTodos = todos; + } + + return filteredTodos; +}; + +export function getItemsLeftCountMessage(activeTodos: Todo[]) { + switch (activeTodos.length) { + case 1: + return '1 items left'; + + case 0: + return 'Everything is done'; + + default: + return `${activeTodos.length} items left`; + } +} From 1c126213c6eb30c5130a533512c06f2330e2868c Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Wed, 27 Sep 2023 10:39:58 +0300 Subject: [PATCH 2/7] add common function for updating todos --- src/App.tsx | 19 +++++++++++++------ src/api/todos.ts | 8 ++++++++ src/components/TodoItem/TodoItem.tsx | 12 +++++++----- src/types/TodoUpdateData.ts | 4 ++++ 4 files changed, 32 insertions(+), 11 deletions(-) create mode 100644 src/types/TodoUpdateData.ts diff --git a/src/App.tsx b/src/App.tsx index 1c8175443c..8fe7522d25 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -8,6 +8,7 @@ import { getTodos, deleteTodo, createTodo, + updateTodo, } from './api/todos'; import { TodoList } from './components/TodoList/TodoList'; import { TodoFilter } from './components/TodoFilter/TodoFilter'; @@ -134,8 +135,10 @@ export const App: React.FC = () => { return; } - client - .patch(`/todos/${todoId}`, { completed: !todoToToggle.completed }) + const todoUpdateData = { completed: !todoToToggle.completed }; + + updateTodo(todoId, todoUpdateData) + .then(() => setErrorMessage(Error.None)) .catch(() => setErrorMessage(Error.Toggle)) .finally(() => { setTogglingId(null); @@ -164,10 +167,14 @@ export const App: React.FC = () => { }; const updateTodos = (todoId: number, data: Todo) => { - return client - .patch(`/todos/${todoId}`, data) - .then(receivedTodo => { - setTodos(todos.map(todo => (todo.id === todoId ? receivedTodo : todo))); + setIsSubmitted(true); + setTogglingId(todoId); + + updateTodo(todoId, data) + .then((receivedTodo) => { + setTodos((prevTodos) => prevTodos + .map((todo) => (todo.id === todoId ? receivedTodo : todo))); + setErrorMessage(Error.None); }) .catch(() => setErrorMessage(Error.Update)) .finally(() => { diff --git a/src/api/todos.ts b/src/api/todos.ts index 3d7651aada..ed40f04a28 100644 --- a/src/api/todos.ts +++ b/src/api/todos.ts @@ -1,4 +1,5 @@ import { Todo } from '../types/Todo'; +import { TodoUpdateData } from '../types/TodoUpdateData'; import { client } from '../utils/fetchClient'; export const getTodos = (userId: number) => { @@ -12,3 +13,10 @@ export const createTodo = ({ title, completed, userId }: Omit) => { export const deleteTodo = (todoId: number) => { return client.delete(`/todos/${todoId}`); }; + +export const updateTodo = ( + todoId: number, + data: TodoUpdateData, +): Promise => { + return client.patch(`/todos/${todoId}`, data); +}; diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx index 606053523d..400c665f89 100644 --- a/src/components/TodoItem/TodoItem.tsx +++ b/src/components/TodoItem/TodoItem.tsx @@ -1,7 +1,8 @@ import React, { useEffect, useRef, useState } from 'react'; import classNames from 'classnames'; import { Todo } from '../../types/Todo'; -import { client } from '../../utils/fetchClient'; +// import { client } from '../../utils/fetchClient'; +import { updateTodo } from '../../api/todos'; type Props = { todo: Todo, @@ -48,11 +49,12 @@ export const TodoItem: React.FC = ({ onDelete(todo.id); } else { setIsEditing(true); - client - .patch(`/todos/${todo.id}`, { title: newTodoTitle }) - .then(() => { + const todoUpdateData = { title: newTodoTitle }; + + updateTodo(todo.id, todoUpdateData) + .then((updatedTodo) => { setIsEditing(false); - onUpdate(todo.id, { ...todo, title: newTodoTitle }); + onUpdate(updatedTodo.id, updatedTodo); }) .catch(() => { setIsEditing(false); diff --git a/src/types/TodoUpdateData.ts b/src/types/TodoUpdateData.ts new file mode 100644 index 0000000000..84010d1dea --- /dev/null +++ b/src/types/TodoUpdateData.ts @@ -0,0 +1,4 @@ +export interface TodoUpdateData { + title?: string, + completed?: boolean; +} From 2f2a44574fe3e6dc0a96a9a95d3332dc4576d786 Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Wed, 27 Sep 2023 13:22:35 +0300 Subject: [PATCH 3/7] fix problem with toggling Todos --- src/App.tsx | 63 ++++++++++++++++++---------- src/components/TodoItem/TodoItem.tsx | 21 +++++++--- src/components/TodoList/TodoList.tsx | 5 ++- 3 files changed, 60 insertions(+), 29 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 8fe7522d25..c29f381f9e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -20,17 +20,34 @@ import { client } from './utils/fetchClient'; const USER_ID = 11521; +function getUpdatedTodos( + todos: Todo[], + updatedTodo: Todo, + updatedField: keyof Todo, +) { + return todos.map(todo => { + if (todo.id === updatedTodo.id) { + return { + ...todo, + [updatedField]: updatedTodo[updatedField], + }; + } + + return todo; + }); +} + export const App: React.FC = () => { const [todos, setTodos] = useState([]); const [status, setStatus] = useState(Status.All); const [errorMessage, setErrorMessage] = useState(Error.None); const [value, setValue] = useState(''); const [isSubmitted, setIsSubmitted] = useState(false); + const [areSubmiting, setAreSubmiting] = useState(false); + const [wasEdited, setWasEdited] = useState(false); const [tempTodo, setTempTodo] = useState(null); const [processingIds, setProcessingIds] = useState([]); - const [areSubmiting, setAreSubmiting] = useState(false); const [togglingId, setTogglingId] = useState(null); - const [wasEdited, setWasEdited] = useState(false); const inputRef = useRef(null); @@ -93,9 +110,7 @@ export const App: React.FC = () => { setIsSubmitted(false); } else { addTodo(newTodo) - .then(() => { - setValue(''); - }) + .then(() => setValue('')) .finally(() => { setTempTodo(null); setIsSubmitted(false); @@ -125,24 +140,26 @@ export const App: React.FC = () => { }); }; - const onToggle = (todoId: number) => { - const todoToToggle = todos.find((todo) => todo.id === todoId); - - setIsSubmitted(true); - setTogglingId(todoId); - - if (!todoToToggle) { - return; - } - - const todoUpdateData = { completed: !todoToToggle.completed }; - - updateTodo(todoId, todoUpdateData) - .then(() => setErrorMessage(Error.None)) - .catch(() => setErrorMessage(Error.Toggle)) + const handleChangeCompletedStatus = ( + todoId: number, + isCompleted: boolean, + ) => { + setProcessingIds(prevState => [...prevState, todoId]); + + return updateTodo(todoId, { completed: !isCompleted }) + .then((currentTodo: Todo) => { + setTodos(prevState => getUpdatedTodos( + prevState, + currentTodo, + 'completed', + )); + }) + .catch(() => { + setErrorMessage(Error.Update); + }) .finally(() => { - setTogglingId(null); - setIsSubmitted(false); + setProcessingIds(prevState => prevState + .filter(id => id !== todoId)); }); }; @@ -227,7 +244,7 @@ export const App: React.FC = () => { todos={visibleTodos} onDelete={onDelete} processingIds={processingIds} - onToggle={onToggle} + onToggle={handleChangeCompletedStatus} togglingId={togglingId} onUpdate={updateTodos} isSubmitted={isSubmitted} diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx index 400c665f89..f5061efa95 100644 --- a/src/components/TodoItem/TodoItem.tsx +++ b/src/components/TodoItem/TodoItem.tsx @@ -1,14 +1,16 @@ -import React, { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import classNames from 'classnames'; import { Todo } from '../../types/Todo'; -// import { client } from '../../utils/fetchClient'; import { updateTodo } from '../../api/todos'; type Props = { todo: Todo, processingIds: number[], onDelete: (id: number) => void, - onToggle: (todoId: number) => void, + onToggle: ( + todoId: number, + isCompleted: boolean, + ) => Promise; togglingId: number | null, onUpdate: (todoId: number, data: Todo) => void, areSubmiting: boolean, @@ -63,6 +65,16 @@ export const TodoItem: React.FC = ({ } }; + const handleChangeCompletedStatus = () => { + onToggle(todo.id, todo.completed) + .then(() => { + }) + .catch((error) => { + // eslint-disable-next-line no-console + console.error(error); + }); + }; + const handleKeyUp = (event: React.KeyboardEvent) => { if (event.key === 'Escape') { setIsEditing(false); @@ -83,8 +95,7 @@ export const TodoItem: React.FC = ({ type="checkbox" className="todo__status" checked={todo.completed} - onClick={() => onToggle(todo.id)} - onChange={() => onUpdate(todo.id, todo)} + onChange={handleChangeCompletedStatus} /> diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx index 652608a294..86c7678231 100644 --- a/src/components/TodoList/TodoList.tsx +++ b/src/components/TodoList/TodoList.tsx @@ -5,7 +5,10 @@ type Props = { todos: Todo[], onDelete: (todoId: number) => void, processingIds: number[], - onToggle: (todoId: number) => void, + onToggle: ( + todoId: number, + isCompleted: boolean, + ) => Promise; togglingId: number | null, onUpdate: (todoId: number, data: Todo) => void, isSubmitted: boolean, From fe0337f7f220048b92025f95069754b980052ac4 Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Wed, 27 Sep 2023 14:10:42 +0300 Subject: [PATCH 4/7] fixed ClearCompletedButton visibility --- src/App.tsx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index c29f381f9e..afda27fc01 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,5 +1,9 @@ /* eslint-disable jsx-a11y/control-has-associated-label */ -import React, { useEffect, useRef, useState } from 'react'; +import React, { + useEffect, + useRef, + useState, +} from 'react'; import classNames from 'classnames'; import { Todo } from './types/Todo'; import { Status } from './types/Status'; @@ -269,7 +273,13 @@ export const App: React.FC = () => { data-cy="ClearCompletedButton" type="button" className="todoapp__clear-completed" - disabled={!completedTodosCount.length} + disabled={!completedTodosCount} + style={{ + visibility: + completedTodosCount.length + ? 'visible' + : 'hidden', + }} onClick={onDeleteCompleted} > Clear completed From 1702c0abc9a90f5ea4673827698f53e435824704 Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Wed, 27 Sep 2023 14:24:00 +0300 Subject: [PATCH 5/7] moved the function to utils --- src/App.tsx | 23 +++++------------------ src/utils/functions.ts | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index afda27fc01..6d2b920621 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -19,28 +19,15 @@ import { TodoFilter } from './components/TodoFilter/TodoFilter'; import { UserWarning } from './UserWarning'; import { TodoError } from './components/TodoError/TodoError'; import { TodoLoadingItem } from './components/TodoLoadingItem/TodoLoadingItem'; -import { filterTodos, getItemsLeftCountMessage } from './utils/functions'; +import { + filterTodos, + getItemsLeftCountMessage, + getUpdatedTodos, +} from './utils/functions'; import { client } from './utils/fetchClient'; const USER_ID = 11521; -function getUpdatedTodos( - todos: Todo[], - updatedTodo: Todo, - updatedField: keyof Todo, -) { - return todos.map(todo => { - if (todo.id === updatedTodo.id) { - return { - ...todo, - [updatedField]: updatedTodo[updatedField], - }; - } - - return todo; - }); -} - export const App: React.FC = () => { const [todos, setTodos] = useState([]); const [status, setStatus] = useState(Status.All); diff --git a/src/utils/functions.ts b/src/utils/functions.ts index 73afcd5276..0984c11017 100644 --- a/src/utils/functions.ts +++ b/src/utils/functions.ts @@ -40,3 +40,20 @@ export function getItemsLeftCountMessage(activeTodos: Todo[]) { return `${activeTodos.length} items left`; } } + +export function getUpdatedTodos( + todos: Todo[], + updatedTodo: Todo, + updatedField: keyof Todo, +) { + return todos.map(todo => { + if (todo.id === updatedTodo.id) { + return { + ...todo, + [updatedField]: updatedTodo[updatedField], + }; + } + + return todo; + }); +} From 6a52aebc7b6e4cb8abdd963bb75ea534a342d1e4 Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Fri, 29 Sep 2023 18:43:29 +0300 Subject: [PATCH 6/7] add suggested changes --- src/App.tsx | 28 +++++++++------- src/components/TodoError/TodoError.tsx | 2 +- src/components/TodoItem/TodoItem.tsx | 33 ++++++++----------- src/components/TodoList/TodoList.tsx | 6 ++-- .../TodoLoadingItem/TodoLoadingItem.tsx | 16 ++------- src/utils/functions.ts | 2 +- 6 files changed, 37 insertions(+), 50 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 6d2b920621..98a303a53e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,3 @@ -/* eslint-disable jsx-a11y/control-has-associated-label */ import React, { useEffect, useRef, @@ -24,7 +23,6 @@ import { getItemsLeftCountMessage, getUpdatedTodos, } from './utils/functions'; -import { client } from './utils/fetchClient'; const USER_ID = 11521; @@ -34,7 +32,7 @@ export const App: React.FC = () => { const [errorMessage, setErrorMessage] = useState(Error.None); const [value, setValue] = useState(''); const [isSubmitted, setIsSubmitted] = useState(false); - const [areSubmiting, setAreSubmiting] = useState(false); + const [isSubmiting, setIsSubmiting] = useState(false); const [wasEdited, setWasEdited] = useState(false); const [tempTodo, setTempTodo] = useState(null); const [processingIds, setProcessingIds] = useState([]); @@ -157,12 +155,18 @@ export const App: React.FC = () => { const toggleAll = () => { const allTodosAreCompleted = todos.length === completedTodosCount.length; - const promiseArray = ( - allTodosAreCompleted - ? completedTodosCount - : activeTodosCount).map((todo: { id: number; completed: boolean; }) => client.patch(`/todos/${todo.id}`, { completed: !todo.completed })); + const todosToUpdate = allTodosAreCompleted + ? completedTodosCount + : activeTodosCount; - setAreSubmiting(true); + const promiseArray = todosToUpdate.map((todo) => { + const { id, completed } = todo; + const updatedCompletedStatus = !completed; + + return updateTodo(id, { completed: updatedCompletedStatus }); + }); + + setIsSubmiting(true); Promise.all(promiseArray) .then(() => { @@ -171,7 +175,7 @@ export const App: React.FC = () => { ))); }) .catch(() => setErrorMessage(Error.Toggle)) - .finally(() => setAreSubmiting(false)); + .finally(() => setIsSubmiting(false)); }; const updateTodos = (todoId: number, data: Todo) => { @@ -201,7 +205,7 @@ export const App: React.FC = () => {
- {todos.length !== 0 && ( + {!!todos.length && (
= ({ errorMessage, onErrorChange }) => { type="button" className="delete" onClick={onErrorChange} + aria-label="Hide Error" /> {errorMessage}
diff --git a/src/components/TodoItem/TodoItem.tsx b/src/components/TodoItem/TodoItem.tsx index f5061efa95..f06afc2349 100644 --- a/src/components/TodoItem/TodoItem.tsx +++ b/src/components/TodoItem/TodoItem.tsx @@ -13,7 +13,7 @@ type Props = { ) => Promise; togglingId: number | null, onUpdate: (todoId: number, data: Todo) => void, - areSubmiting: boolean, + isSubmiting: boolean, }; export const TodoItem: React.FC = ({ @@ -23,7 +23,7 @@ export const TodoItem: React.FC = ({ onToggle, togglingId, onUpdate, - areSubmiting, + isSubmiting, }) => { const [isEditing, setIsEditing] = useState(false); const [newTodoTitle, setNewTodoTitle] = useState(todo.title); @@ -47,7 +47,7 @@ export const TodoItem: React.FC = ({ if (newTodoTitle === currentTodoTitle) { setIsEditing(false); - } else if (newTodoTitle.trim() === '') { + } else if (!newTodoTitle.trim()) { onDelete(todo.id); } else { setIsEditing(true); @@ -66,13 +66,7 @@ export const TodoItem: React.FC = ({ }; const handleChangeCompletedStatus = () => { - onToggle(todo.id, todo.completed) - .then(() => { - }) - .catch((error) => { - // eslint-disable-next-line no-console - console.error(error); - }); + onToggle(todo.id, todo.completed); }; const handleKeyUp = (event: React.KeyboardEvent) => { @@ -81,6 +75,11 @@ export const TodoItem: React.FC = ({ } }; + const isActive = () => { + return processingIds.includes(todo.id) + || togglingId === todo.id || isSubmiting; + }; + return (
= ({ {isEditing ? (
setNewTodoTitle(event.target.value)} @@ -130,9 +129,7 @@ export const TodoItem: React.FC = ({ className="todo__remove" data-cy="TodoDelete" onClick={() => onDelete(todo.id)} - disabled={processingIds.includes(todo.id) - || togglingId === todo.id - || areSubmiting} + disabled={isActive()} > × @@ -141,9 +138,7 @@ export const TodoItem: React.FC = ({ data-cy="TodoLoader" className={classNames( 'modal overlay', { - 'is-active': processingIds.includes(todo.id) - || togglingId === todo.id - || areSubmiting, + 'is-active': isActive(), }, )} > diff --git a/src/components/TodoList/TodoList.tsx b/src/components/TodoList/TodoList.tsx index 86c7678231..9517eb6cf4 100644 --- a/src/components/TodoList/TodoList.tsx +++ b/src/components/TodoList/TodoList.tsx @@ -12,7 +12,7 @@ type Props = { togglingId: number | null, onUpdate: (todoId: number, data: Todo) => void, isSubmitted: boolean, - areSubmiting: boolean, + isSubmiting: boolean, }; export const TodoList: React.FC = ({ @@ -22,7 +22,7 @@ export const TodoList: React.FC = ({ onToggle, togglingId, onUpdate, - areSubmiting, + isSubmiting, }) => (
{todos.map((todo) => ( @@ -34,7 +34,7 @@ export const TodoList: React.FC = ({ onToggle={onToggle} togglingId={togglingId} onUpdate={onUpdate} - areSubmiting={areSubmiting} + isSubmiting={isSubmiting} /> ))}
diff --git a/src/components/TodoLoadingItem/TodoLoadingItem.tsx b/src/components/TodoLoadingItem/TodoLoadingItem.tsx index b4ff9c4841..a7713db542 100644 --- a/src/components/TodoLoadingItem/TodoLoadingItem.tsx +++ b/src/components/TodoLoadingItem/TodoLoadingItem.tsx @@ -17,24 +17,12 @@ export const TodoLoadingItem: React.FC = ({ tempTodo, isSubmitted }) => { checked /> - + {tempTodo?.title} - - {/* */} -
diff --git a/src/utils/functions.ts b/src/utils/functions.ts index 0984c11017..23ada5b060 100644 --- a/src/utils/functions.ts +++ b/src/utils/functions.ts @@ -31,7 +31,7 @@ export const filterTodos = (todos: Todo[], filterStatus: Status): Todo[] => { export function getItemsLeftCountMessage(activeTodos: Todo[]) { switch (activeTodos.length) { case 1: - return '1 items left'; + return '1 item left'; case 0: return 'Everything is done'; From 5253f25e93c31cb3e9c6e390f1d771e5d580d53d Mon Sep 17 00:00:00 2001 From: Viktoriia Roik Date: Sat, 30 Sep 2023 18:18:30 +0300 Subject: [PATCH 7/7] add suggested changes --- src/App.tsx | 20 ++++++++++++-------- src/styles/todoapp.scss | 4 ++++ src/utils/functions.ts | 9 +++------ 3 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 98a303a53e..926085ac19 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -47,11 +47,19 @@ export const App: React.FC = () => { }, []); useEffect(() => { + let timer: NodeJS.Timeout; + if (errorMessage) { - setTimeout(() => { + timer = setTimeout(() => { setErrorMessage(Error.None); }, 3000); } + + return () => { + if (timer) { + clearTimeout(timer); + } + }; }, [errorMessage]); useEffect(() => { @@ -264,14 +272,10 @@ export const App: React.FC = () => {