-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
solution 0.01 one test failed #1532
Open
StanislavKapytsia
wants to merge
3
commits into
mate-academy:master
Choose a base branch
from
StanislavKapytsia: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 2 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 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 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,300 @@ | ||
/* 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, | ||
useRef, | ||
useState, | ||
} from 'react'; | ||
import { addTodo, delTodo, get, updTodo } from './api/todos'; | ||
import { TodoInterface } from './types/Todo'; | ||
import { Filter } from './types/filter'; | ||
import { TodoList } from './components/todoList/TodoList'; | ||
import { FilteredTodoList } from './components/footer/FilteredTodoList'; | ||
import classNames from 'classnames'; | ||
|
||
export const App: React.FC = () => { | ||
if (!USER_ID) { | ||
return <UserWarning />; | ||
} | ||
const [todos, setTodos] = useState<TodoInterface[]>([]); | ||
const [filter, setFilter] = useState<Filter>(Filter.All); | ||
const [value, setValue] = useState(''); | ||
const [tempTodo, setTempTodo] = useState<TodoInterface | null>(null); | ||
const [errorMessage, setErrorMessage] = useState(''); | ||
const [todosForModify, setTodosForModify] = useState<TodoInterface[]>([]); | ||
|
||
const inputForFocusRef = useRef<HTMLInputElement>(null); | ||
const notificationRef = useRef<HTMLDivElement>(null); | ||
|
||
const hideNotification = useCallback(() => { | ||
if (notificationRef.current) { | ||
notificationRef.current.classList.add('hidden'); | ||
} | ||
}, []); | ||
|
||
const errorHandling = (error: Error) => { | ||
if (notificationRef.current) { | ||
notificationRef.current.classList.remove('hidden'); | ||
setErrorMessage(error.message); | ||
setTimeout(() => { | ||
if (notificationRef.current) { | ||
notificationRef.current.classList.add('hidden'); | ||
} | ||
}, 3000); | ||
} | ||
}; | ||
|
||
const newId = () => { | ||
const maxId = Math.max(0, ...todos.map(todo => todo.id)); | ||
|
||
return maxId + 1; | ||
}; | ||
|
||
const errorManagement = (er: unknown) => { | ||
if (er instanceof Error) { | ||
errorHandling(er); | ||
} | ||
}; | ||
|
||
const createTodo = (id: number, title: string): TodoInterface => ({ | ||
id, | ||
userId: 2039, | ||
title: title.trim(), | ||
completed: false, | ||
}); | ||
|
||
useEffect(() => { | ||
if (inputForFocusRef.current) { | ||
inputForFocusRef.current.focus(); | ||
} | ||
|
||
const fetchTodos = async () => { | ||
try { | ||
hideNotification(); | ||
|
||
const data = await get(); | ||
|
||
setTodos(data); | ||
} catch (error) { | ||
if (error instanceof Error) { | ||
errorHandling(error); | ||
} | ||
} | ||
}; | ||
|
||
fetchTodos(); | ||
}, [hideNotification]); | ||
|
||
const allTodosComplited = useMemo(() => { | ||
return todos.every(item => item.completed); | ||
}, [todos]); | ||
|
||
const [active, setActive] = useState(allTodosComplited); | ||
|
||
useEffect(() => { | ||
setActive(allTodosComplited); | ||
}, [allTodosComplited]); | ||
|
||
useEffect(() => { | ||
if (inputForFocusRef.current && !tempTodo) { | ||
inputForFocusRef.current.focus(); | ||
} | ||
}, [tempTodo]); | ||
|
||
const deleteTodos = async (content: number[], inputEdit?: boolean) => { | ||
for (const todoId of content) { | ||
try { | ||
hideNotification(); | ||
await delTodo(todoId); | ||
// await new Promise(resolve => setTimeout(resolve, 2000)); for checking delete/save every single todo; | ||
|
||
setTodos(current => current.filter(item => todoId !== item.id)); | ||
} catch (error) { | ||
errorManagement(error); | ||
} | ||
} | ||
|
||
if (inputForFocusRef.current && !inputEdit) { | ||
inputForFocusRef.current.focus(); | ||
} | ||
|
||
setTodosForModify([]); | ||
}; | ||
|
||
const addTodos = async (data: string) => { | ||
if (inputForFocusRef.current) { | ||
inputForFocusRef.current.focus(); | ||
} | ||
|
||
setTempTodo(() => createTodo(0, data)); | ||
|
||
try { | ||
hideNotification(); | ||
|
||
await addTodo(data); | ||
|
||
const newTodo = createTodo(newId(), data); | ||
|
||
setTodos(current => [...current, newTodo]); | ||
|
||
setValue(''); | ||
} catch (error) { | ||
errorManagement(error); | ||
setValue(value); | ||
} finally { | ||
setTempTodo(null); | ||
} | ||
}; | ||
|
||
const updateTodos = async (updateTodo: TodoInterface[]) => { | ||
for (const upTodo of updateTodo) { | ||
try { | ||
const updatedTodo = (await updTodo(upTodo)) as TodoInterface; | ||
|
||
setTodos(current => { | ||
const newTodosList = [...current]; | ||
const index = newTodosList.findIndex(todo => todo.id === upTodo.id); | ||
|
||
newTodosList.splice(index, 1, updatedTodo); | ||
|
||
return newTodosList; | ||
}); | ||
|
||
if (inputForFocusRef.current) { | ||
inputForFocusRef.current.focus(); | ||
} | ||
} catch (error) { | ||
errorManagement(error); | ||
} | ||
} | ||
|
||
setTodosForModify([]); | ||
}; | ||
|
||
const handleClose = () => { | ||
if (notificationRef.current) { | ||
notificationRef.current.classList.add('hidden'); | ||
} | ||
}; | ||
|
||
const filteredTodos = useMemo(() => { | ||
return todos.filter(todo => { | ||
switch (filter) { | ||
case Filter.All: | ||
return true; | ||
case Filter.Active: | ||
return !todo.completed; | ||
case Filter.Completed: | ||
return todo.completed; | ||
default: | ||
return true; | ||
} | ||
}); | ||
}, [todos, filter]); | ||
|
||
const handleChangeValue = (e: React.ChangeEvent<HTMLInputElement>) => { | ||
if (notificationRef.current) { | ||
notificationRef.current.classList.add('hidden'); | ||
} | ||
|
||
setValue(e.target.value); | ||
}; | ||
|
||
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => { | ||
e.preventDefault(); | ||
|
||
if (value.trim()) { | ||
addTodos(value); | ||
} else { | ||
const empty = new Error('Title should not be empty'); | ||
|
||
errorHandling(empty); | ||
setValue(''); | ||
} | ||
}; | ||
|
||
const handleUpdateStatus = async () => { | ||
const copyTodos = [...todos]; | ||
|
||
let content; | ||
|
||
if (active) { | ||
content = copyTodos.map(item => ({ ...item, completed: false })); | ||
} else { | ||
content = copyTodos | ||
.filter(todo => !todo.completed) | ||
.map(item => ({ ...item, completed: true })); | ||
} | ||
|
||
setTodosForModify(content); | ||
|
||
await Promise.allSettled(content.map(todo => updateTodos([todo]))); | ||
|
||
setTodosForModify([]); | ||
}; | ||
|
||
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 className="todoapp__header"> | ||
{todos.length > 0 && ( | ||
<button | ||
type="button" | ||
className={classNames('todoapp__toggle-all', { active: active })} | ||
data-cy="ToggleAllButton" | ||
onClick={handleUpdateStatus} | ||
/> | ||
)} | ||
|
||
<form onSubmit={onSubmit}> | ||
<input | ||
ref={inputForFocusRef} | ||
data-cy="NewTodoField" | ||
type="text" | ||
className="todoapp__new-todo" | ||
placeholder="What needs to be done?" | ||
value={value} | ||
onChange={handleChangeValue} | ||
disabled={tempTodo !== null} | ||
/> | ||
</form> | ||
</header> | ||
|
||
{todos.length > 0 && ( | ||
<TodoList | ||
filteredTodos={filteredTodos} | ||
deleteTodos={deleteTodos} | ||
tempTodo={tempTodo} | ||
setTodosForModify={setTodosForModify} | ||
todosForModify={todosForModify} | ||
updateTodos={updateTodos} | ||
/> | ||
)} | ||
|
||
{todos.length > 0 && ( | ||
<FilteredTodoList | ||
todos={todos} | ||
setFilter={setFilter} | ||
filter={filter} | ||
deleteTodos={deleteTodos} | ||
setTodosForModify={setTodosForModify} | ||
/> | ||
)} | ||
</div> | ||
|
||
<div | ||
ref={notificationRef} | ||
data-cy="ErrorNotification" | ||
className="notification | ||
is-danger is-light has-text-weight-normal hidden" | ||
> | ||
<button | ||
data-cy="HideErrorButton" | ||
type="button" | ||
className="delete" | ||
onClick={handleClose} | ||
/> | ||
{errorMessage} | ||
</div> | ||
</div> | ||
); | ||
}; |
This file contains 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,55 @@ | ||
import { TodoInterface } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const USER_ID = 2039; | ||
|
||
export const get = async () => { | ||
try { | ||
const todos = await client.get<TodoInterface[]>(`/todos?userId=${USER_ID}`); | ||
|
||
return todos; | ||
} catch (error) { | ||
throw new Error('Unable to load todos'); | ||
} | ||
}; | ||
|
||
export const delTodo = async (id: number) => { | ||
try { | ||
const deleteTodo = await client.delete(`/todos/${id}`); | ||
|
||
return deleteTodo; | ||
} catch (error) { | ||
throw new Error('Unable to delete a todo'); | ||
} | ||
}; | ||
|
||
export const addTodo = async (title: string) => { | ||
try { | ||
const adTodo = await client.post(`/todos/`, { | ||
completed: false, | ||
title, | ||
userId: 2039, | ||
}); | ||
|
||
return adTodo; | ||
} catch (error) { | ||
throw new Error('Unable to add a todo'); | ||
} | ||
}; | ||
|
||
export const updTodo = async (updateTodo: TodoInterface) => { | ||
const { id, title, completed, userId } = updateTodo; | ||
|
||
try { | ||
const upTodo = await client.patch(`/todos/${id}`, { | ||
id, | ||
completed, | ||
title, | ||
userId, | ||
}); | ||
|
||
return upTodo; | ||
} catch (error) { | ||
throw new Error('Unable to update a todo'); | ||
} | ||
}; |
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.
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.