-
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 #1543
base: master
Are you sure you want to change the base?
add task solution #1543
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,203 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
/* eslint-disable jsx-a11y/label-has-associated-control */ | ||
import React, { useEffect, useState } from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
|
||
const USER_ID = 0; | ||
import { | ||
addTodos, | ||
deleteTodos, | ||
getTodos, | ||
updateTodos, | ||
USER_ID, | ||
} from './api/todos'; | ||
import { Todo } from './types/Todo'; | ||
import { Filter } from './types/Filter'; | ||
import { Header } from './components/Header/Header'; | ||
import { TodoList } from './components/TodoList/TodoList'; | ||
import { Footer } from './components/Footer/Footer'; | ||
import { ErrorNotification } from './components/ErrorNotification/ErrorNotification'; | ||
import { filterTodos } from './utils/getFilteredTodos'; | ||
|
||
export const App: React.FC = () => { | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [errorMessage, setErrorMessage] = useState(''); | ||
const [filterStatus, setFilterStatus] = useState<Filter>(Filter.All); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [isLoading, setIsLoading] = useState(false); | ||
const [editTodos, setEditTodos] = useState<number[]>([]); | ||
|
||
const filteredTodos = filterTodos(todos, filterStatus); | ||
|
||
const handleCreateTodo = async (newTodo: Omit<Todo, 'id'>) => { | ||
setErrorMessage(''); | ||
setTempTodo({ id: 0, ...newTodo }); | ||
setIsLoading(true); | ||
try { | ||
const createdTodo = await addTodos(newTodo); | ||
|
||
setTodos(prev => [...prev, createdTodo]); | ||
} catch (error) { | ||
setErrorMessage('Unable to add a todo'); | ||
|
||
throw error; | ||
} finally { | ||
setTempTodo(null); | ||
setIsLoading(false); | ||
} | ||
}; | ||
|
||
const handleDeleteTodo = async (id: number) => { | ||
setErrorMessage(''); | ||
setIsLoading(true); | ||
setEditTodos(current => [...current, id]); | ||
try { | ||
await deleteTodos(id); | ||
setTodos(prev => prev.filter(todo => todo.id !== id)); | ||
} catch { | ||
setEditTodos([]); | ||
setErrorMessage('Unable to delete a todo'); | ||
} finally { | ||
setIsLoading(false); | ||
} | ||
}; | ||
|
||
const handleClearCompleted = async () => { | ||
const completedTodos = todos.filter(todo => todo.completed); | ||
|
||
await Promise.all(completedTodos.map(todo => handleDeleteTodo(todo.id))); | ||
}; | ||
|
||
const handleToggleStatus = async (id: number, completed: boolean) => { | ||
setIsLoading(true); | ||
setEditTodos(current => [...current, id]); | ||
try { | ||
const todoToUpdate = todos.find(todo => todo.id === id); | ||
|
||
if (!todoToUpdate) { | ||
setErrorMessage('Todo not found'); | ||
|
||
return; | ||
} | ||
|
||
const updatedTodo = await updateTodos(id, { | ||
completed, | ||
userId: todoToUpdate.userId, | ||
title: todoToUpdate.title, | ||
}); | ||
|
||
setTodos(prev => | ||
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)), | ||
); | ||
} catch { | ||
setErrorMessage('Unable to update a todo'); | ||
} finally { | ||
setEditTodos(prev => prev.filter(todoId => todoId !== id)); | ||
setIsLoading(false); | ||
} | ||
}; | ||
|
||
const handleToggleAll = async () => { | ||
const allCompleted = todos.every(todo => todo.completed); | ||
const newStatus = !allCompleted; | ||
|
||
setIsLoading(true); | ||
const promises = todos | ||
.filter(todo => todo.completed !== newStatus) | ||
.map(todo => handleToggleStatus(todo.id, newStatus)); | ||
|
||
try { | ||
await Promise.all(promises); | ||
setTodos(prev => | ||
prev.map(todo => | ||
todo.completed !== newStatus | ||
? { ...todo, completed: newStatus } | ||
: todo, | ||
), | ||
); | ||
} catch { | ||
setErrorMessage('Unable to update todos'); | ||
} finally { | ||
setIsLoading(false); | ||
} | ||
}; | ||
|
||
const handleUpdateTitle = async (id: number, newTitle: string) => { | ||
setErrorMessage(''); | ||
setIsLoading(true); | ||
setEditTodos(current => [...current, id]); | ||
|
||
try { | ||
const todoToUpdate = todos.find(todo => todo.id === id); | ||
|
||
if (!todoToUpdate) { | ||
return; | ||
} | ||
|
||
const updatedTodo = await updateTodos(id, { | ||
...todoToUpdate, | ||
title: newTitle, | ||
}); | ||
|
||
setTodos(prev => | ||
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)), | ||
); | ||
} catch { | ||
setErrorMessage('Unable to update a todo'); | ||
throw new Error('Unable to update a todo'); | ||
} finally { | ||
setIsLoading(false); | ||
setEditTodos(prev => prev.filter(todoId => todoId !== id)); | ||
} | ||
}; | ||
|
||
useEffect(() => { | ||
getTodos() | ||
.then(setTodos) | ||
.catch(() => setErrorMessage('Unable to load todos')); | ||
}, []); | ||
|
||
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"> | ||
<Header | ||
todos={todos} | ||
setErrorMessage={setErrorMessage} | ||
handleCreateTodo={handleCreateTodo} | ||
isLoading={isLoading} | ||
onToggleAll={handleToggleAll} | ||
/> | ||
|
||
{todos.length > 0 && ( | ||
<TodoList | ||
todos={filteredTodos} | ||
tempTodo={tempTodo} | ||
onDelete={handleDeleteTodo} | ||
editTodos={editTodos} | ||
onToggle={handleToggleStatus} | ||
onUpdate={handleUpdateTitle} | ||
/> | ||
)} | ||
|
||
{!!todos.length && ( | ||
<Footer | ||
filterStatus={filterStatus} | ||
setFilterStatus={setFilterStatus} | ||
todos={todos} | ||
handleClearCompleted={handleClearCompleted} | ||
/> | ||
)} | ||
</div> | ||
|
||
<ErrorNotification | ||
errorMessage={errorMessage} | ||
setErrorMessage={setErrorMessage} | ||
/> | ||
</div> | ||
); | ||
}; |
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 = 2125; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
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. let's move /todos into constant and reuse |
||
}; | ||
|
||
export const addTodos = (newTodo: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>(`/todos`, newTodo); | ||
}; | ||
|
||
export const deleteTodos = (id: number) => { | ||
return client.delete(`/todos/${id}`); | ||
}; | ||
|
||
export const updateTodos = (id: number, newTodo: Omit<Todo, 'id'>) => { | ||
return client.patch<Todo>(`/todos/${id}`, newTodo); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import React, { useEffect } from 'react'; | ||
import cn from 'classnames'; | ||
|
||
type Props = { | ||
errorMessage: string; | ||
setErrorMessage: (message: string) => void; | ||
}; | ||
|
||
export const ErrorNotification: React.FC<Props> = ({ | ||
errorMessage, | ||
setErrorMessage, | ||
}) => { | ||
useEffect(() => { | ||
if (errorMessage) { | ||
const timer = setTimeout(() => { | ||
setErrorMessage(''); | ||
}, 3000); | ||
|
||
return () => clearTimeout(timer); | ||
} | ||
|
||
return undefined; | ||
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. do we really need to return undefined here? |
||
}, [errorMessage, setErrorMessage]); | ||
|
||
return ( | ||
<div | ||
className={cn('notification is-danger is-light has-text-weight-normal', { | ||
hidden: !errorMessage, | ||
})} | ||
data-cy="ErrorNotification" | ||
> | ||
<button | ||
data-cy="HideErrorButton" | ||
type="button" | ||
className="delete" | ||
onClick={() => setErrorMessage('')} | ||
/> | ||
{errorMessage} | ||
</div> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import React from 'react'; | ||
import { Todo } from '../../types/Todo'; | ||
import { Filter } from '../../types/Filter'; | ||
import cn from 'classnames'; | ||
|
||
type Props = { | ||
todos: Todo[]; | ||
filterStatus: Filter; | ||
setFilterStatus: (filter: Filter) => void; | ||
handleClearCompleted: () => void; | ||
}; | ||
|
||
const filterLinks = [ | ||
{ label: 'All', value: Filter.All }, | ||
{ label: 'Active', value: Filter.Active }, | ||
{ label: 'Completed', value: Filter.Completed }, | ||
]; | ||
|
||
export const Footer: React.FC<Props> = ({ | ||
setFilterStatus, | ||
todos, | ||
filterStatus, | ||
handleClearCompleted, | ||
}) => { | ||
const todosLeft = todos.filter(todo => !todo.completed); | ||
const isClearCompletedDisabled = todos.every(todo => !todo.completed); | ||
|
||
return ( | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
<span className="todo-count" data-cy="TodosCounter"> | ||
{todosLeft.length} items left | ||
</span> | ||
|
||
<nav className="filter" data-cy="Filter"> | ||
{filterLinks.map(({ label, value }) => ( | ||
<a | ||
key={value} | ||
href={`#/${value}`} | ||
className={cn('filter__link', { selected: filterStatus === value })} | ||
data-cy={`FilterLink${label}`} | ||
onClick={() => setFilterStatus(value)} | ||
> | ||
{label} | ||
</a> | ||
))} | ||
Comment on lines
+35
to
+45
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. that's good! |
||
</nav> | ||
|
||
<button | ||
type="button" | ||
className="todoapp__clear-completed" | ||
data-cy="ClearCompletedButton" | ||
disabled={isClearCompletedDisabled} | ||
onClick={handleClearCompleted} | ||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
); | ||
}; |
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.
try to make
enum
for all errors