-
Notifications
You must be signed in to change notification settings - Fork 2.1k
React Todo App with API task #2135
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
Open
devTym
wants to merge
3
commits into
mate-academy:master
Choose a base branch
from
devTym:develop
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,259 @@ | ||
| /* 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 React, { useEffect, useRef, useState } from 'react'; | ||
| import { UserWarning } from './UserWarning'; | ||
|
|
||
| const USER_ID = 0; | ||
| import { | ||
| createTodo, | ||
| deleteTodo, | ||
| getTodos, | ||
| updateTodo, | ||
| USER_ID, | ||
| } from './api/todos'; | ||
| import { Todo } from './types/Todo'; | ||
| import { TODO_STATUS, TodoStatus } from './types/TodoStatus'; | ||
| import { ErrorNotification } from './components/ErrorNotification'; | ||
| import { TodoList } from './components/TodoList'; | ||
| import { TodoFooter } from './components/TodoFooter'; | ||
| import { TodoHeader } from './components/TodoHeader'; | ||
| import { ErrorMessage } from './types/ErrorMessage'; | ||
|
|
||
| export const App: React.FC = () => { | ||
| const [todos, setTodos] = useState<Todo[]>([]); | ||
|
|
||
| const [todoQuery, setTodoQuery] = useState(''); | ||
| const [isAdding, setIsAdding] = useState(false); | ||
| const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
| const newTodoRef = useRef<HTMLInputElement>(null); | ||
| const focusNewTodo = () => { | ||
| setTimeout(() => newTodoRef.current?.focus(), 0); | ||
| }; | ||
|
|
||
| const [editedTodoId, setEditedTodoId] = useState<number | null>(null); | ||
|
|
||
| const [todosStatusFilter, setTodoStatusFilter] = useState<TodoStatus>( | ||
| TODO_STATUS.ALL, | ||
| ); | ||
| const [loadingTodoIds, setloadingTodoIds] = useState<number[]>([]); | ||
| const [errorMessage, setErrorMessage] = useState<ErrorMessage | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| getTodos() | ||
| .then(data => { | ||
| setTodos(data); | ||
| }) | ||
| .catch(() => { | ||
| setErrorMessage(ErrorMessage.LoadTodos); | ||
| }); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| if (!errorMessage) { | ||
| return; | ||
| } | ||
|
|
||
| const timerId = setTimeout(() => { | ||
| setErrorMessage(null); | ||
| }, 3000); | ||
|
|
||
| return () => { | ||
| clearTimeout(timerId); | ||
| }; | ||
| }, [errorMessage]); | ||
|
|
||
| const { | ||
| active: todosActiveCount, | ||
| completed: todosCompletedCount, | ||
| filtered: filteredTodos, | ||
| } = todos.reduce( | ||
| (acc, todo) => { | ||
| const active = acc.active + (todo.completed ? 0 : 1); | ||
| const completed = acc.completed + (todo.completed ? 1 : 0); | ||
|
|
||
| const shouldInclude = | ||
| todosStatusFilter === TODO_STATUS.ALL || | ||
| (todosStatusFilter === TODO_STATUS.ACTIVE && !todo.completed) || | ||
| (todosStatusFilter === TODO_STATUS.COMPLETED && todo.completed); | ||
|
|
||
| return { | ||
| active, | ||
| completed, | ||
| filtered: shouldInclude ? [...acc.filtered, todo] : acc.filtered, | ||
| }; | ||
| }, | ||
| { active: 0, completed: 0, filtered: [] as Todo[] }, | ||
| ); | ||
|
|
||
| const isAllCompleted = | ||
| todos.length > 0 && todos.length === todosCompletedCount; | ||
|
|
||
| const handleAddTodo = async () => { | ||
| setErrorMessage(null); | ||
|
|
||
| const trimmed = todoQuery.trim(); | ||
|
|
||
| if (!trimmed) { | ||
| setErrorMessage(ErrorMessage.EmptyTitle); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (isAdding) { | ||
| return; | ||
| } | ||
|
|
||
| setIsAdding(true); | ||
| setTempTodo({ | ||
| id: -1, | ||
| userId: USER_ID, | ||
| title: trimmed, | ||
| completed: false, | ||
| }); | ||
|
|
||
| try { | ||
| const createdTodo = await createTodo({ | ||
| userId: USER_ID, | ||
| title: trimmed, | ||
| completed: false, | ||
| }); | ||
|
|
||
| setTodos(prev => [...prev, createdTodo]); | ||
| setTodoQuery(''); | ||
| } catch { | ||
| setErrorMessage(ErrorMessage.AddTodo); | ||
| } finally { | ||
| setTempTodo(null); | ||
| setIsAdding(false); | ||
| focusNewTodo(); | ||
| } | ||
| }; | ||
|
|
||
| const handleDeleteTodo = async (id: number) => { | ||
| if (loadingTodoIds.includes(id)) { | ||
| return; | ||
| } | ||
|
|
||
| setloadingTodoIds(prev => [...prev, id]); | ||
|
|
||
| try { | ||
| await deleteTodo(id); | ||
| setTodos(prev => prev.filter(todo => todo.id !== id)); | ||
| focusNewTodo(); | ||
| } catch (error) { | ||
| setErrorMessage(ErrorMessage.DeleteTodo); | ||
| } finally { | ||
| setloadingTodoIds(prev => prev.filter(todoId => todoId !== id)); | ||
| } | ||
| }; | ||
|
|
||
| const handleClearCompleted = async () => { | ||
| setErrorMessage(null); | ||
|
|
||
| const completedIds = todos.filter(t => t.completed).map(t => t.id); | ||
|
|
||
| await Promise.all(completedIds.map(id => handleDeleteTodo(id))); | ||
|
|
||
| focusNewTodo(); | ||
| }; | ||
|
|
||
| const handleEditTodo = async ( | ||
| todo: Todo, | ||
| data: Partial<Omit<Todo, 'id' | 'userId'>>, | ||
| ) => { | ||
| if (loadingTodoIds.includes(todo.id)) { | ||
| return; | ||
| } | ||
|
|
||
| setErrorMessage(null); | ||
| setloadingTodoIds(prev => | ||
| prev.includes(todo.id) ? prev : [...prev, todo.id], | ||
| ); | ||
|
|
||
| try { | ||
| const updated = await updateTodo(todo.id, data); | ||
|
|
||
| setTodos(prev => | ||
| prev.map(currentTodo => | ||
| currentTodo.id === todo.id ? updated : currentTodo, | ||
| ), | ||
| ); | ||
| } catch { | ||
| setErrorMessage(ErrorMessage.UpdateTodo); | ||
| throw new Error(ErrorMessage.UpdateTodo); | ||
| } finally { | ||
| setloadingTodoIds(prev => prev.filter(id => id !== todo.id)); | ||
| } | ||
| }; | ||
|
|
||
| const handleSetTodoStatus = async (todo: Todo, completed: boolean) => { | ||
| return handleEditTodo(todo, { completed }); | ||
| }; | ||
|
|
||
| const handleToggleAllStatus = async () => { | ||
| setErrorMessage(null); | ||
|
|
||
| const targetCompleted = todosCompletedCount < todos.length ? true : false; | ||
|
|
||
| await Promise.all( | ||
| todos | ||
| .filter(todo => todo.completed != targetCompleted) | ||
| .map(todo => handleEditTodo(todo, { completed: targetCompleted })), | ||
| ); | ||
| }; | ||
|
|
||
| const handleSelectTodoStatus = (todoStatus: TodoStatus) => { | ||
| setTodoStatusFilter(todoStatus); | ||
| }; | ||
|
|
||
| if (!USER_ID) { | ||
| return <UserWarning />; | ||
| } | ||
|
|
||
| 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 | ||
| newTodoQuery={todoQuery} | ||
| onNewTodoQueryChange={setTodoQuery} | ||
| shouldFocusNewTodo={editedTodoId === null} | ||
| inputRef={newTodoRef} | ||
| onAddTodo={handleAddTodo} | ||
| isAllCompleted={isAllCompleted} | ||
| isToggleBtn={todos.length > 0} | ||
| isAdding={isAdding} | ||
| onToggleAllStatus={handleToggleAllStatus} | ||
| /> | ||
|
|
||
| {(filteredTodos.length > 0 || tempTodo) && ( | ||
| <TodoList | ||
| todos={filteredTodos} | ||
| tempTodo={tempTodo} | ||
| onToggleTodoStatus={handleSetTodoStatus} | ||
| loadingTodoIds={loadingTodoIds} | ||
| editedTodoId={editedTodoId} | ||
| setEditedTodoId={setEditedTodoId} | ||
| onDeleteTodo={handleDeleteTodo} | ||
| onEditTodo={handleEditTodo} | ||
| /> | ||
| )} | ||
| {todos.length > 0 && ( | ||
| <TodoFooter | ||
| todosActiveCount={todosActiveCount} | ||
| todosStatusFilter={todosStatusFilter} | ||
| onSelectStatusFilter={handleSelectTodoStatus} | ||
| disableClearCompletedBtn={todosCompletedCount === 0} | ||
| onClearCompleted={handleClearCompleted} | ||
| /> | ||
| )} | ||
| </div> | ||
|
|
||
| <ErrorNotification | ||
| message={errorMessage} | ||
| onClose={() => setErrorMessage(null)} | ||
| /> | ||
| </div> | ||
| </> | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { Todo } from '../types/Todo'; | ||
| import { client } from '../utils/fetchClient'; | ||
|
|
||
| export const USER_ID = 3982; | ||
|
|
||
| export const getTodos = () => { | ||
| return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
| }; | ||
|
|
||
| export const createTodo = (data: Omit<Todo, 'id'>) => { | ||
| return client.post<Todo>(`/todos`, data); | ||
| }; | ||
|
|
||
| export const deleteTodo = (id: number) => { | ||
| return client.delete(`/todos/${id}`); | ||
| }; | ||
|
|
||
| export const updateTodo = (id: number, data: Partial<Omit<Todo, 'id'>>) => { | ||
| return client.patch<Todo>(`/todos/${id}`, { ...data, userId: USER_ID }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import clsx from 'clsx'; | ||
| import React from 'react'; | ||
| import { ErrorMessage } from '../../types/ErrorMessage'; | ||
|
|
||
| type Props = { | ||
| message: ErrorMessage | null; | ||
| onClose: () => void; | ||
| }; | ||
|
|
||
| export const ErrorNotification: React.FC<Props> = ({ message, onClose }) => { | ||
| return ( | ||
| <div | ||
| data-cy="ErrorNotification" | ||
| className={clsx( | ||
| 'notification is-danger is-light has-text-weight-normal', | ||
| { | ||
| hidden: !message, | ||
| }, | ||
| )} | ||
| > | ||
| <button | ||
| data-cy="HideErrorButton" | ||
| type="button" | ||
| className="delete" | ||
| onClick={onClose} | ||
| /> | ||
| {message} | ||
| </div> | ||
| ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from './ErrorNotification'; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.