-
Notifications
You must be signed in to change notification settings - Fork 2.1k
react_todo-app-with-api_solution #2201
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
Banderos14
wants to merge
4
commits into
mate-academy:master
Choose a base branch
from
Banderos14: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
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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,344 @@ | ||
| /* eslint-disable max-len */ | ||
| /* eslint-disable jsx-a11y/control-has-associated-label */ | ||
| import React from 'react'; | ||
| import React, { | ||
| FormEvent, | ||
| KeyboardEvent, | ||
| useEffect, | ||
| useMemo, | ||
| useRef, | ||
| useState, | ||
| } from 'react'; | ||
| import { UserWarning } from './UserWarning'; | ||
|
|
||
| const USER_ID = 0; | ||
| import { API_URL, ErrorMessage, RESPONSE_DELAY } from './constants/todos'; | ||
| import { ErrorNotification } from './components/ErrorNotification'; | ||
| import { Footer } from './components/Footer'; | ||
| import { Header } from './components/Header'; | ||
| import { TodoList } from './components/TodoList'; | ||
| import { Filter } from './types/Filter'; | ||
| import { Todo } from './types/Todo'; | ||
| import { getUserId } from './utils/getUserId'; | ||
| import { request } from './utils/request'; | ||
| import { wait } from './utils/wait'; | ||
|
|
||
| export const App: React.FC = () => { | ||
| if (!USER_ID) { | ||
| const userId = getUserId(); | ||
| const [todos, setTodos] = useState<Todo[]>([]); | ||
| const [filter, setFilter] = useState<Filter>('all'); | ||
| const [newTitle, setNewTitle] = useState(''); | ||
| const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
| const [isAdding, setIsAdding] = useState(false); | ||
| const [processingIds, setProcessingIds] = useState<number[]>([]); | ||
| const [errorMessage, setErrorMessage] = useState(''); | ||
| const [editingId, setEditingId] = useState<number | null>(null); | ||
| const [editingTitle, setEditingTitle] = useState(''); | ||
|
|
||
| const errorTimerId = useRef<ReturnType<typeof setTimeout> | null>(null); | ||
| const newTodoField = useRef<HTMLInputElement>(null); | ||
| const editField = useRef<HTMLInputElement>(null); | ||
|
|
||
| const showError = (message: ErrorMessage) => { | ||
| setErrorMessage(message); | ||
|
|
||
| if (errorTimerId.current) { | ||
| clearTimeout(errorTimerId.current); | ||
| } | ||
|
|
||
| errorTimerId.current = setTimeout(() => { | ||
| setErrorMessage(''); | ||
| }, 3000); | ||
| }; | ||
|
|
||
| const hideError = () => { | ||
| setErrorMessage(''); | ||
|
|
||
| if (errorTimerId.current) { | ||
| clearTimeout(errorTimerId.current); | ||
| } | ||
| }; | ||
|
|
||
| const focusNewTodoField = () => { | ||
| setTimeout(() => newTodoField.current?.focus(), 0); | ||
| }; | ||
|
|
||
| const addProcessingId = (id: number) => { | ||
| setProcessingIds(current => [...current, id]); | ||
| }; | ||
|
|
||
| const removeProcessingId = (id: number) => { | ||
| setProcessingIds(current => current.filter(currentId => currentId !== id)); | ||
| }; | ||
|
|
||
| const loadTodos = async () => { | ||
| try { | ||
| const loadedTodos = await request<Todo[]>(`${API_URL}?userId=${userId}`); | ||
|
|
||
| setTodos(loadedTodos); | ||
| } catch { | ||
| showError(ErrorMessage.Load); | ||
| } finally { | ||
| focusNewTodoField(); | ||
| } | ||
| }; | ||
|
|
||
| useEffect(() => { | ||
| if (userId) { | ||
| loadTodos(); | ||
| } | ||
|
|
||
| return () => { | ||
| if (errorTimerId.current) { | ||
| clearTimeout(errorTimerId.current); | ||
| } | ||
| }; | ||
| }, [userId]); // eslint-disable-line react-hooks/exhaustive-deps | ||
|
|
||
| useEffect(() => { | ||
| if (editingId !== null) { | ||
| editField.current?.focus(); | ||
| } | ||
| }, [editingId]); | ||
|
|
||
| const visibleTodos = useMemo(() => { | ||
| switch (filter) { | ||
| case 'active': | ||
| return todos.filter(todo => !todo.completed); | ||
|
|
||
| case 'completed': | ||
| return todos.filter(todo => todo.completed); | ||
|
|
||
| default: | ||
| return todos; | ||
| } | ||
| }, [filter, todos]); | ||
|
|
||
| const activeTodosCount = todos.filter(todo => !todo.completed).length; | ||
| const completedTodosCount = todos.length - activeTodosCount; | ||
| const allTodosCompleted = todos.length > 0 && activeTodosCount === 0; | ||
| const shouldShowTempTodo = tempTodo && filter !== 'completed'; | ||
|
|
||
| const createTodo = async (event: FormEvent) => { | ||
| event.preventDefault(); | ||
| hideError(); | ||
|
|
||
| const title = newTitle.trim(); | ||
|
|
||
| if (!title) { | ||
| showError(ErrorMessage.EmptyTitle); | ||
| focusNewTodoField(); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| const optimisticTodo: Todo = { | ||
| id: 0, | ||
| userId, | ||
| title, | ||
| completed: false, | ||
| }; | ||
|
|
||
| setTempTodo(optimisticTodo); | ||
| setIsAdding(true); | ||
|
|
||
| try { | ||
| const createdTodo = await request<Todo>(API_URL, { | ||
| method: 'POST', | ||
| body: JSON.stringify({ | ||
| userId, | ||
| title, | ||
| completed: false, | ||
| }), | ||
| }); | ||
|
|
||
| await wait(RESPONSE_DELAY); | ||
| setTodos(current => [...current, createdTodo]); | ||
| setNewTitle(''); | ||
| } catch { | ||
| showError(ErrorMessage.Add); | ||
| } finally { | ||
| setIsAdding(false); | ||
| setTempTodo(null); | ||
| focusNewTodoField(); | ||
| } | ||
| }; | ||
|
|
||
| const deleteTodo = async (todoId: number, shouldFocusNewTodo = true) => { | ||
| hideError(); | ||
| addProcessingId(todoId); | ||
|
|
||
| try { | ||
| await fetch(`${API_URL}/${todoId}`, { | ||
| method: 'DELETE', | ||
| }).then(response => { | ||
| if (!response.ok) { | ||
| throw new Error(String(response.status)); | ||
| } | ||
| }); | ||
|
|
||
| await wait(RESPONSE_DELAY); | ||
| setTodos(current => current.filter(todo => todo.id !== todoId)); | ||
|
|
||
| if (editingId === todoId) { | ||
| setEditingId(null); | ||
| } | ||
| } catch { | ||
| showError(ErrorMessage.Delete); | ||
| throw new Error(ErrorMessage.Delete); | ||
| } finally { | ||
| removeProcessingId(todoId); | ||
| if (shouldFocusNewTodo) { | ||
| focusNewTodoField(); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| const updateTodo = async ( | ||
| todoId: number, | ||
| data: Partial<Pick<Todo, 'title' | 'completed'>>, | ||
| ) => { | ||
| hideError(); | ||
| addProcessingId(todoId); | ||
|
|
||
| try { | ||
| const updatedTodo = await request<Todo>(`${API_URL}/${todoId}`, { | ||
| method: 'PATCH', | ||
| body: JSON.stringify(data), | ||
| }); | ||
|
|
||
| await wait(RESPONSE_DELAY); | ||
| setTodos(current => | ||
| current.map(todo => | ||
| todo.id === todoId ? { ...todo, ...updatedTodo } : todo, | ||
| ), | ||
| ); | ||
|
|
||
| return updatedTodo; | ||
| } catch { | ||
| showError(ErrorMessage.Update); | ||
| throw new Error(ErrorMessage.Update); | ||
| } finally { | ||
| removeProcessingId(todoId); | ||
| } | ||
| }; | ||
|
|
||
| const toggleTodo = (todo: Todo) => { | ||
| updateTodo(todo.id, { completed: !todo.completed }).catch(() => {}); | ||
| }; | ||
|
|
||
| const toggleAll = async () => { | ||
| const completed = !allTodosCompleted; | ||
| const todosToUpdate = todos.filter(todo => todo.completed !== completed); | ||
|
|
||
| await Promise.all( | ||
| todosToUpdate.map(todo => | ||
| updateTodo(todo.id, { completed }).catch(() => undefined), | ||
| ), | ||
| ); | ||
| }; | ||
|
|
||
| const deleteCompletedTodos = async () => { | ||
| await Promise.all( | ||
| todos | ||
| .filter(todo => todo.completed) | ||
| .map(todo => deleteTodo(todo.id).catch(() => undefined)), | ||
| ); | ||
| }; | ||
|
|
||
| const startEditing = (todo: Todo) => { | ||
| setEditingId(todo.id); | ||
| setEditingTitle(todo.title); | ||
| }; | ||
|
|
||
| const cancelEditing = () => { | ||
| setEditingId(null); | ||
| setEditingTitle(''); | ||
| }; | ||
|
|
||
| const saveEditing = async (todo: Todo) => { | ||
| const title = editingTitle.trim(); | ||
|
|
||
| if (title === todo.title) { | ||
| cancelEditing(); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (!title) { | ||
| try { | ||
| await deleteTodo(todo.id, false); | ||
| } catch { | ||
| return; | ||
| } | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| try { | ||
| await updateTodo(todo.id, { title }); | ||
| cancelEditing(); | ||
| } catch { | ||
| editField.current?.focus(); | ||
| } | ||
| }; | ||
|
|
||
| const handleEditSubmit = (event: FormEvent, todo: Todo) => { | ||
| event.preventDefault(); | ||
| saveEditing(todo); | ||
| }; | ||
|
|
||
| const handleEditKeyUp = (event: KeyboardEvent<HTMLInputElement>) => { | ||
| if (event.key === 'Escape') { | ||
| cancelEditing(); | ||
| } | ||
| }; | ||
|
|
||
| if (!userId) { | ||
| 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"> | ||
| <Header | ||
| todosCount={todos.length} | ||
| allTodosCompleted={allTodosCompleted} | ||
| newTitle={newTitle} | ||
| isAdding={isAdding} | ||
| newTodoField={newTodoField} | ||
| onNewTitleChange={setNewTitle} | ||
| onCreateTodo={createTodo} | ||
| onToggleAll={toggleAll} | ||
| /> | ||
|
|
||
| {(todos.length > 0 || shouldShowTempTodo) && ( | ||
| <TodoList | ||
| todos={visibleTodos} | ||
| tempTodo={shouldShowTempTodo ? tempTodo : null} | ||
| editingId={editingId} | ||
| editingTitle={editingTitle} | ||
| processingIds={processingIds} | ||
| editField={editField} | ||
| onToggleTodo={toggleTodo} | ||
| onDeleteTodo={todoId => deleteTodo(todoId).catch(() => {})} | ||
| onStartEditing={startEditing} | ||
| onEditingTitleChange={setEditingTitle} | ||
| onEditSubmit={handleEditSubmit} | ||
| onEditBlur={saveEditing} | ||
| onEditKeyUp={handleEditKeyUp} | ||
| /> | ||
| )} | ||
|
|
||
| {todos.length > 0 && ( | ||
| <Footer | ||
| activeTodosCount={activeTodosCount} | ||
| completedTodosCount={completedTodosCount} | ||
| selectedFilter={filter} | ||
| onFilterChange={setFilter} | ||
| onDeleteCompletedTodos={deleteCompletedTodos} | ||
| /> | ||
| )} | ||
| </div> | ||
|
|
||
| <ErrorNotification message={errorMessage} onHide={hideError} /> | ||
| </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,25 @@ | ||
| import React from 'react'; | ||
| import classNames from 'classnames'; | ||
|
|
||
| type Props = { | ||
| message: string; | ||
| onHide: () => void; | ||
| }; | ||
|
|
||
| export const ErrorNotification: React.FC<Props> = ({ message, onHide }) => ( | ||
| <div | ||
| className={classNames( | ||
| 'notification is-danger is-light has-text-weight-normal', | ||
| { hidden: !message }, | ||
| )} | ||
| data-cy="ErrorNotification" | ||
| > | ||
| <button | ||
| type="button" | ||
| className="delete" | ||
| data-cy="HideErrorButton" | ||
| onClick={onHide} | ||
| /> | ||
| {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.
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.