-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Add task solution #1497
base: master
Are you sure you want to change the base?
Add task solution #1497
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,293 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
|
||
const USER_ID = 0; | ||
import React, { useCallback, useEffect, useMemo, useState } from 'react'; | ||
import { | ||
getTodos, | ||
addTodo, | ||
deleteTodo, | ||
USER_ID, | ||
toggleTodo, | ||
updateTodoTitle, | ||
} from './api/todos'; | ||
import { Todo } from './types/Todo'; | ||
import { Header } from './components/Header'; | ||
import { Footer } from './components/Footer'; | ||
import { ErrorNotification } from './components/ErrorNotification'; | ||
import { FilterStates, ErrorMessages } from './types/enums'; | ||
import { TodoItem } from './components/TodoItem'; | ||
|
||
export const App: React.FC = () => { | ||
if (!USER_ID) { | ||
return <UserWarning />; | ||
} | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [error, setError] = useState<string | null>(null); | ||
const [filter, setFilter] = useState(FilterStates.ALL); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [title, setTitle] = useState(''); | ||
const [isAdding, setIsAdding] = useState(false); | ||
const [isEditingId, setIsEditingId] = useState<number | null>(null); | ||
|
||
const handleAddTodo = useCallback(async (): Promise<void> => { | ||
if (title.trim() === '') { | ||
setError(ErrorMessages.NAMING_TODOS); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Create a variable for trimmed |
||
setTimeout(() => setError(null), 3000); | ||
|
||
return; | ||
} | ||
|
||
setIsAdding(true); | ||
|
||
try { | ||
const newTempTodo: Todo = { | ||
id: 0, | ||
userId: USER_ID, | ||
title, | ||
completed: false, | ||
}; | ||
|
||
setTempTodo(newTempTodo); | ||
|
||
const newTodo = await addTodo(title.trim()); | ||
|
||
setTodos(prevTodos => [...prevTodos, newTodo]); | ||
setTempTodo(null); | ||
setTitle(''); | ||
} catch { | ||
setError(ErrorMessages.ADDING_TODOS); | ||
setTempTodo(null); | ||
setTimeout(() => setError(null), 3000); | ||
} finally { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider clearing timeouts when the component unmounts to avoid potential memory leaks and ensure smooth handling of state updates. This will improve the reliability of your code and prevent errors in case the DOM element is no longer available. |
||
setIsAdding(false); | ||
setTimeout(() => { | ||
const input = | ||
document.querySelector<HTMLInputElement>('.todoapp__new-todo'); | ||
|
||
input?.focus(); | ||
}, 100); | ||
} | ||
}, [title]); | ||
|
||
const handleDeleteTodo = useCallback( | ||
async (todoId: number): Promise<void> => { | ||
try { | ||
await deleteTodo(todoId); | ||
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== todoId)); | ||
} catch { | ||
setError(ErrorMessages.DELETING_TODOS); | ||
setTimeout(() => setError(null), 3000); | ||
} finally { | ||
const input = | ||
document.querySelector<HTMLInputElement>('.todoapp__new-todo'); | ||
|
||
input?.focus(); | ||
} | ||
}, | ||
[], | ||
); | ||
|
||
const handleToggleTodoStatus = useCallback( | ||
async (todoId: number, completed: boolean): Promise<void> => { | ||
try { | ||
await toggleTodo(todoId, completed); | ||
setTodos(prevTodos => | ||
prevTodos.map(todo => | ||
todo.id === todoId ? { ...todo, completed } : todo, | ||
), | ||
); | ||
} catch { | ||
setError(ErrorMessages.UPDATE_TODOS); | ||
setTimeout(() => setError(null), 3000); | ||
} | ||
}, | ||
[], | ||
); | ||
|
||
const handleUpdateTodoTitle = useCallback( | ||
async (todoId: number, newTitle: string): Promise<void> => { | ||
const existingTodo = todos.find(todo => todo.id === todoId); | ||
|
||
if (!existingTodo) { | ||
return; | ||
} | ||
|
||
if (newTitle.trim() === existingTodo.title) { | ||
setIsEditingId(null); | ||
|
||
return; | ||
} | ||
|
||
if (newTitle.trim() === '') { | ||
try { | ||
await deleteTodo(todoId); | ||
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== todoId)); | ||
setIsEditingId(null); | ||
} catch { | ||
setError(ErrorMessages.DELETING_TODOS); | ||
setTimeout(() => setError(null), 3000); | ||
} | ||
|
||
return; | ||
} | ||
|
||
try { | ||
await updateTodoTitle(todoId, newTitle); | ||
setTodos(prevTodos => | ||
prevTodos.map(todo => | ||
todo.id === todoId ? { ...todo, title: newTitle } : todo, | ||
), | ||
); | ||
setIsEditingId(null); | ||
} catch { | ||
setError(ErrorMessages.UPDATE_TODOS); | ||
setTimeout(() => setError(null), 3000); | ||
} | ||
}, | ||
[todos], | ||
); | ||
|
||
const handleDoubleClick = useCallback((todoId: number) => { | ||
setIsEditingId(todoId); | ||
}, []); | ||
|
||
const filteredTodos = useMemo(() => { | ||
return todos.filter(todo => { | ||
switch (filter) { | ||
case FilterStates.ACTIVE: | ||
return !todo.completed; | ||
case FilterStates.COMPLETED: | ||
return todo.completed; | ||
default: | ||
return true; | ||
} | ||
}); | ||
}, [todos, filter]); | ||
|
||
const hasTodos = todos.length > 0; | ||
const allCompleted = todos.length > 0 && todos.every(todo => todo.completed); | ||
|
||
const handleToggleAllTodos = useCallback(async () => { | ||
const newCompletedState = !allCompleted; | ||
|
||
try { | ||
const updatePromises = todos.map(async todo => { | ||
if (todo.completed !== newCompletedState) { | ||
await toggleTodo(todo.id, newCompletedState); | ||
|
||
return { ...todo, completed: newCompletedState }; | ||
} | ||
|
||
return todo; | ||
}); | ||
|
||
const updatedTodos = await Promise.all(updatePromises); | ||
|
||
setTodos(updatedTodos); | ||
} catch { | ||
setError(ErrorMessages.UPDATE_TODOS); | ||
setTimeout(() => setError(null), 3000); | ||
} | ||
}, [todos, allCompleted]); | ||
|
||
const handleClearCompleted = useCallback(async (): Promise<void> => { | ||
const completedTodos = todos.filter(todo => todo.completed); | ||
|
||
try { | ||
const deletionResults = await Promise.allSettled( | ||
completedTodos.map(todo => handleDeleteTodo(todo.id)), | ||
); | ||
|
||
const hasErrors = deletionResults.some( | ||
result => result.status === 'rejected', | ||
); | ||
|
||
if (hasErrors) { | ||
setError('Unable to delete some completed todos'); | ||
setTimeout(() => { | ||
setError(null); | ||
}, 3000); | ||
} | ||
} catch { | ||
setError('Unable to clear completed todos'); | ||
setTimeout(() => { | ||
setError(null); | ||
}, 3000); | ||
} | ||
}, [handleDeleteTodo, todos]); | ||
|
||
const handleHideError = () => { | ||
setError(null); | ||
}; | ||
|
||
const handleCancelEdit = (event: React.KeyboardEvent) => { | ||
if (event.key === 'Escape') { | ||
setIsEditingId(null); | ||
} | ||
}; | ||
|
||
useEffect(() => { | ||
const fetchTodos = async () => { | ||
try { | ||
const data = await getTodos(); | ||
|
||
setTodos(data); | ||
} catch (err) { | ||
setError(ErrorMessages.LOAD_TODOS); | ||
const timer = setTimeout(() => setError(null), 3000); | ||
|
||
return () => clearTimeout(timer); | ||
} | ||
}; | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Move the |
||
fetchTodos(); | ||
}, []); | ||
|
||
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 | ||
allCompleted={allCompleted} | ||
onAddTodo={handleAddTodo} | ||
onToggleAllTodos={handleToggleAllTodos} | ||
title={title} | ||
setTitle={setTitle} | ||
todoCount={todos.length} | ||
isAdding={isAdding} | ||
setError={setError} | ||
/> | ||
|
||
{hasTodos && | ||
filteredTodos.map(todo => ( | ||
<TodoItem | ||
key={todo.id} | ||
todo={todo} | ||
onDelete={handleDeleteTodo} | ||
onToggleStatus={handleToggleTodoStatus} | ||
onUpdateTitle={handleUpdateTodoTitle} | ||
setError={setError} | ||
isEditing={isEditingId === todo.id} | ||
onDoubleClick={() => handleDoubleClick(todo.id)} | ||
onCancelEdit={event => handleCancelEdit(event)} | ||
/> | ||
))} | ||
|
||
{tempTodo && ( | ||
<TodoItem | ||
todo={tempTodo} | ||
onDelete={handleDeleteTodo} | ||
onToggleStatus={handleToggleTodoStatus} | ||
onUpdateTitle={handleUpdateTodoTitle} | ||
setError={setError} | ||
isAdding={isAdding} | ||
/> | ||
)} | ||
|
||
{hasTodos && ( | ||
<Footer | ||
todos={todos} | ||
filter={filter} | ||
setFilter={setFilter} | ||
onClearCompleted={handleClearCompleted} | ||
/> | ||
)} | ||
</div> | ||
<ErrorNotification error={error} onHideError={handleHideError} /> | ||
</div> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const USER_ID = 1625; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const addTodo = (title: string) => { | ||
return client.post<Todo>(`/todos`, { | ||
title, | ||
userId: USER_ID, | ||
completed: false, | ||
}); | ||
}; | ||
|
||
export const deleteTodo = (todoId: number) => { | ||
return client.delete(`/todos/${todoId}`); | ||
}; | ||
|
||
export const toggleTodo = (todoId: number, completed: boolean) => { | ||
return client.patch(`/todos/${todoId}`, { completed }); | ||
}; | ||
|
||
export const updateTodoTitle = (todoId: number, title: string) => { | ||
return client.patch(`/todos/${todoId}`, { title }); | ||
}; |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,35 @@ | ||||||
import React from 'react'; | ||||||
import classNames from 'classnames'; | ||||||
|
||||||
interface ErrorNotificationProps { | ||||||
error: string | null; | ||||||
onHideError: () => void; | ||||||
} | ||||||
|
||||||
export const ErrorNotification: React.FC<ErrorNotificationProps> = ({ | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
error, | ||||||
onHideError, | ||||||
}) => { | ||||||
return ( | ||||||
<div | ||||||
data-cy="ErrorNotification" | ||||||
className={classNames( | ||||||
'notification', | ||||||
'is-danger', | ||||||
'is-light', | ||||||
'has-text-weight-normal', | ||||||
{ | ||||||
hidden: !error, | ||||||
}, | ||||||
)} | ||||||
> | ||||||
<button | ||||||
data-cy="HideErrorButton" | ||||||
type="button" | ||||||
className="delete" | ||||||
onClick={onHideError} | ||||||
/> | ||||||
{error} | ||||||
</div> | ||||||
); | ||||||
}; |
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.