-
Notifications
You must be signed in to change notification settings - Fork 2.1k
add task solution #2194
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
AndrewPrszn
wants to merge
2
commits into
mate-academy:master
Choose a base branch
from
AndrewPrszn: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
add task solution #2194
Changes from all commits
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,263 @@ | ||
| /* eslint-disable jsx-a11y/label-has-associated-control */ | ||
| /* eslint-disable max-len */ | ||
| /* eslint-disable jsx-a11y/control-has-associated-label */ | ||
| import React from 'react'; | ||
|
|
||
| import React, { useEffect, useMemo, useRef } from 'react'; | ||
|
|
||
| import { UserWarning } from './UserWarning'; | ||
| import { USER_ID } from './api/todos'; | ||
| import { Todo } from './types/Todo'; | ||
| import { getTodos, addTodo, deleteTodo, updateTodo } from './api/todos'; | ||
|
|
||
| const USER_ID = 0; | ||
| import { Header } from './components/Header'; | ||
| import { TodoList } from './components/TodoList'; | ||
| import { Footer } from './components/Footer'; | ||
| import { ErrorNotification } from './components/ErrorNotification'; | ||
| import { Filter } from './types/Filter'; | ||
| import { ErrorMessage } from './types/ErrorMessage'; | ||
|
|
||
| export const App: React.FC = () => { | ||
| const [todos, setTodos] = React.useState<Todo[]>([]); | ||
| const [error, setError] = React.useState<string | null>(null); | ||
| const [newTitle, setNewTitle] = React.useState(''); | ||
| const [tempTodo, setTempTodo] = React.useState<Todo | null>(null); | ||
| const [isAdding, setIsAdding] = React.useState(false); | ||
| const [deleteIds, setDeleteIds] = React.useState<number[]>([]); | ||
| const [filter, setFilter] = React.useState<Filter>(Filter.All); | ||
| const [loadingIds, setLoadingIds] = React.useState<number[]>([]); | ||
|
|
||
| const inputRef = useRef<HTMLInputElement>(null); | ||
|
|
||
| const loadTodos = async () => { | ||
| try { | ||
| const data = await getTodos(); | ||
|
|
||
| setTodos(data); | ||
| } catch { | ||
| setTodos([]); | ||
| setError(ErrorMessage.Load); | ||
| } | ||
| }; | ||
|
|
||
| useEffect(() => { | ||
| setTimeout(loadTodos, 0); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| if (!error) { | ||
| return; | ||
| } | ||
|
|
||
| const timer = setTimeout(() => setError(null), 3000); | ||
|
|
||
| return () => clearTimeout(timer); | ||
| }, [error]); | ||
|
|
||
| useEffect(() => { | ||
| inputRef.current?.focus(); | ||
| }); | ||
|
|
||
| const activeCount = todos.filter(t => !t.completed).length; | ||
| const hasCompleted = todos.some(t => t.completed); | ||
| const allCompleted = todos.length > 0 && activeCount === 0; | ||
|
|
||
| const visibleTodos = useMemo(() => { | ||
| switch (filter) { | ||
| case Filter.Active: | ||
| return todos.filter(t => !t.completed); | ||
| case Filter.Completed: | ||
| return todos.filter(t => t.completed); | ||
| default: | ||
| return todos; | ||
| } | ||
| }, [todos, filter]); | ||
|
|
||
| const handleAddTodo = async (e: React.FormEvent) => { | ||
| e.preventDefault(); | ||
|
|
||
| const trimmed = newTitle.trim(); | ||
|
|
||
| if (!trimmed) { | ||
| setError(ErrorMessage.EmptyTitle); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| const temp: Todo = { | ||
| id: 0, | ||
| title: trimmed, | ||
| completed: false, | ||
| userId: USER_ID, | ||
| }; | ||
|
|
||
| setTempTodo(temp); | ||
| setIsAdding(true); | ||
|
|
||
| try { | ||
| const created = await addTodo({ | ||
| title: trimmed, | ||
| completed: false, | ||
| userId: USER_ID, | ||
| }); | ||
|
|
||
| setTodos(prev => [...prev, created]); | ||
| setNewTitle(''); | ||
| } catch { | ||
| setError(ErrorMessage.Add); | ||
| } finally { | ||
| setTempTodo(null); | ||
| setIsAdding(false); | ||
| } | ||
| }; | ||
|
|
||
| const handleDeleteTodo = async (id: number) => { | ||
| setDeleteIds(prev => [...prev, id]); | ||
|
|
||
| try { | ||
| await deleteTodo(id); | ||
| setTodos(prev => prev.filter(t => t.id !== id)); | ||
| } catch { | ||
| setError(ErrorMessage.Delete); | ||
| } finally { | ||
| setDeleteIds(prev => prev.filter(x => x !== id)); | ||
| } | ||
| }; | ||
|
|
||
| const handleClearCompleted = async () => { | ||
| const completed = todos.filter(t => t.completed); | ||
|
|
||
| const results = await Promise.allSettled( | ||
| completed.map(t => deleteTodo(t.id)), | ||
| ); | ||
|
|
||
| const okIds: number[] = []; | ||
|
|
||
| results.forEach((r, i) => { | ||
| if (r.status === 'fulfilled') { | ||
| okIds.push(completed[i].id); | ||
| } | ||
| }); | ||
|
|
||
| setTodos(prev => prev.filter(t => !okIds.includes(t.id))); | ||
|
|
||
| if (results.some(r => r.status === 'rejected')) { | ||
| setError(ErrorMessage.Delete); | ||
| } | ||
| }; | ||
|
|
||
| const handleToggleTodo = async (todo: Todo) => { | ||
| setLoadingIds(prev => [...prev, todo.id]); | ||
|
|
||
| try { | ||
| const updated = await updateTodo(todo.id, { | ||
| completed: !todo.completed, | ||
| }); | ||
|
|
||
| setTodos(prev => prev.map(t => (t.id === todo.id ? updated : t))); | ||
| } catch { | ||
| setError(ErrorMessage.Update); | ||
| } finally { | ||
| setLoadingIds(prev => prev.filter(id => id !== todo.id)); | ||
| } | ||
| }; | ||
|
|
||
| const handleToggleAll = async () => { | ||
| const newStatus = !allCompleted; | ||
|
|
||
| const toUpdate = todos.filter(t => t.completed !== newStatus); | ||
|
|
||
| await Promise.all( | ||
| toUpdate.map(async todo => { | ||
| setLoadingIds(prev => [...prev, todo.id]); | ||
|
|
||
| try { | ||
| const updated = await updateTodo(todo.id, { | ||
| completed: newStatus, | ||
| }); | ||
|
|
||
| setTodos(prev => prev.map(t => (t.id === todo.id ? updated : t))); | ||
| } catch { | ||
| setError(ErrorMessage.Update); | ||
| } finally { | ||
| setLoadingIds(prev => prev.filter(id => id !== todo.id)); | ||
| } | ||
| }), | ||
| ); | ||
| }; | ||
|
|
||
| if (!USER_ID) { | ||
| return <UserWarning />; | ||
| } | ||
|
|
||
| const handleRename = async (todo: Todo, update: string) => { | ||
| const trimmed = update.trim(); | ||
|
|
||
| if (trimmed === todo.title) { | ||
| return; | ||
| } | ||
|
|
||
| if (!trimmed) { | ||
| await handleDeleteTodo(todo.id); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| setLoadingIds(prev => [...prev, todo.id]); | ||
|
|
||
| try { | ||
| const updated = await updateTodo(todo.id, { | ||
| title: trimmed, | ||
| }); | ||
|
|
||
| setTodos(prev => prev.map(t => (t.id === todo.id ? updated : t))); | ||
| } catch { | ||
| setError(ErrorMessage.Update); | ||
|
|
||
| throw new Error('Unable to update'); | ||
| } finally { | ||
| setLoadingIds(prev => prev.filter(id => id !== todo.id)); | ||
| } | ||
| }; | ||
|
|
||
| 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 | ||
| newTitle={newTitle} | ||
| setNewTitle={setNewTitle} | ||
| onSubmit={handleAddTodo} | ||
| isAdding={isAdding} | ||
| inputRef={inputRef} | ||
| allCompleted={allCompleted} | ||
| hasTodos={todos.length > 0} | ||
| onToggleAll={handleToggleAll} | ||
| /> | ||
|
|
||
| <TodoList | ||
| todos={visibleTodos} | ||
| deleteIds={deleteIds} | ||
| loadingIds={loadingIds} | ||
| onDelete={handleDeleteTodo} | ||
| onToggle={handleToggleTodo} | ||
| onRename={handleRename} | ||
| tempTodo={tempTodo} | ||
| isAdding={isAdding} | ||
| /> | ||
|
|
||
| {todos.length > 0 && ( | ||
| <Footer | ||
| activeCount={activeCount} | ||
| filter={filter} | ||
| setFilter={setFilter} | ||
| hasCompleted={hasCompleted} | ||
| onClearCompleted={handleClearCompleted} | ||
| /> | ||
| )} | ||
| </div> | ||
|
|
||
| <ErrorNotification error={error} onClose={() => setError(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,23 @@ | ||
| import { Todo } from '../types/Todo'; | ||
| import { client } from '../utils/fetchClient'; | ||
|
|
||
| export const USER_ID = 4139; | ||
|
|
||
| export const getTodos = () => { | ||
| return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
| }; | ||
|
|
||
| export const addTodo = (todo: Omit<Todo, 'id'>) => { | ||
| return client.post<Todo>('/todos', { | ||
| ...todo, | ||
| userId: USER_ID, | ||
| }); | ||
| }; | ||
|
|
||
| export const deleteTodo = (id: number) => { | ||
| return client.delete(`/todos/${id}`); | ||
| }; | ||
|
|
||
| export const updateTodo = (id: number, updates: Partial<Omit<Todo, 'id'>>) => { | ||
| return client.patch<Todo>(`/todos/${id}`, updates); | ||
| }; |
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,26 @@ | ||
| import React from 'react'; | ||
|
|
||
| type Props = { | ||
| error: string | null; | ||
| onClose: () => void; | ||
| }; | ||
|
|
||
| export const ErrorNotification: React.FC<Props> = ({ error, onClose }) => { | ||
| return ( | ||
| <div | ||
| data-cy="ErrorNotification" | ||
| className={`notification is-danger is-light has-text-weight-normal ${ | ||
| error ? '' : 'hidden' | ||
| }`} | ||
| > | ||
| <button | ||
| data-cy="HideErrorButton" | ||
| type="button" | ||
| className="delete" | ||
| onClick={onClose} | ||
| /> | ||
|
|
||
| {error} | ||
| </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,59 @@ | ||
| import React from 'react'; | ||
| import { Filter } from '../types/Filter'; | ||
|
|
||
| type Props = { | ||
| activeCount: number; | ||
| filter: Filter; | ||
| setFilter: (value: Filter) => void; | ||
| hasCompleted: boolean; | ||
| onClearCompleted: () => void; | ||
| }; | ||
|
|
||
| const filters = [ | ||
| { label: 'All', value: Filter.All, href: '#/' }, | ||
| { label: 'Active', value: Filter.Active, href: '#/active' }, | ||
| { label: 'Completed', value: Filter.Completed, href: '#/completed' }, | ||
| ]; | ||
|
|
||
| export const Footer: React.FC<Props> = ({ | ||
| activeCount, | ||
| filter, | ||
| setFilter, | ||
| hasCompleted, | ||
| onClearCompleted, | ||
| }) => { | ||
| return ( | ||
| <footer className="todoapp__footer" data-cy="Footer"> | ||
| <span className="todo-count" data-cy="TodosCounter"> | ||
| {activeCount} items left | ||
| </span> | ||
|
|
||
| <nav className="filter" data-cy="Filter"> | ||
| {filters.map(f => ( | ||
| <a | ||
| key={f.value} | ||
| href={f.href} | ||
| className={`filter__link ${filter === f.value ? 'selected' : ''}`} | ||
| onClick={e => { | ||
| e.preventDefault(); | ||
| setFilter(f.value); | ||
| }} | ||
| data-cy={`FilterLink${f.label}`} | ||
| > | ||
| {f.label} | ||
| </a> | ||
| ))} | ||
| </nav> | ||
|
|
||
| <button | ||
| type="button" | ||
| className="todoapp__clear-completed" | ||
| data-cy="ClearCompletedButton" | ||
| disabled={!hasCompleted} | ||
| onClick={onClearCompleted} | ||
| > | ||
| Clear completed | ||
| </button> | ||
| </footer> | ||
| ); | ||
| }; | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
move to separate fn