-
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
Solution #814
Open
viktoria-roik
wants to merge
7
commits into
mate-academy:master
Choose a base branch
from
viktoria-roik: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
Solution #814
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
aabb460
first version of TodoApp, not all tests are completed
viktoria-roik 1c12621
add common function for updating todos
viktoria-roik 2f2a445
fix problem with toggling Todos
viktoria-roik fe0337f
fixed ClearCompletedButton visibility
viktoria-roik 1702c0a
moved the function to utils
viktoria-roik 6a52aeb
add suggested changes
viktoria-roik 5253f25
add suggested changes
viktoria-roik 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,24 +1,292 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import React, { | ||
useEffect, | ||
useRef, | ||
useState, | ||
} from 'react'; | ||
import classNames from 'classnames'; | ||
import { Todo } from './types/Todo'; | ||
import { Status } from './types/Status'; | ||
import { Error } from './types/Error'; | ||
import { | ||
getTodos, | ||
deleteTodo, | ||
createTodo, | ||
updateTodo, | ||
} from './api/todos'; | ||
import { TodoList } from './components/TodoList/TodoList'; | ||
import { TodoFilter } from './components/TodoFilter/TodoFilter'; | ||
import { UserWarning } from './UserWarning'; | ||
import { TodoError } from './components/TodoError/TodoError'; | ||
import { TodoLoadingItem } from './components/TodoLoadingItem/TodoLoadingItem'; | ||
import { | ||
filterTodos, | ||
getItemsLeftCountMessage, | ||
getUpdatedTodos, | ||
} from './utils/functions'; | ||
|
||
const USER_ID = 0; | ||
const USER_ID = 11521; | ||
|
||
export const App: React.FC = () => { | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [status, setStatus] = useState<Status>(Status.All); | ||
const [errorMessage, setErrorMessage] = useState(Error.None); | ||
const [value, setValue] = useState(''); | ||
const [isSubmitted, setIsSubmitted] = useState(false); | ||
const [isSubmiting, setIsSubmiting] = useState(false); | ||
const [wasEdited, setWasEdited] = useState(false); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [processingIds, setProcessingIds] = useState<number[]>([]); | ||
const [togglingId, setTogglingId] = useState<number | null>(null); | ||
|
||
const inputRef = useRef<HTMLInputElement | null>(null); | ||
|
||
useEffect(() => { | ||
getTodos(USER_ID) | ||
.then(setTodos) | ||
.catch(() => setErrorMessage(Error.Load)); | ||
}, []); | ||
|
||
useEffect(() => { | ||
if (errorMessage) { | ||
setTimeout(() => { | ||
setErrorMessage(Error.None); | ||
}, 3000); | ||
} | ||
}, [errorMessage]); | ||
|
||
useEffect(() => { | ||
if (wasEdited) { | ||
inputRef.current?.focus(); | ||
} | ||
}, [wasEdited]); | ||
|
||
const visibleTodos = filterTodos(todos, status); | ||
|
||
const activeTodosCount = todos.filter(todo => !todo.completed); | ||
const completedTodosCount = todos.filter(todo => todo.completed); | ||
|
||
function addTodo({ userId, title, completed }: Todo): Promise<void> { | ||
setErrorMessage(Error.None); | ||
setWasEdited(false); | ||
|
||
return createTodo({ userId, title, completed }) | ||
.then(newTodo => { | ||
setTodos(currentTodos => [...currentTodos, newTodo]); | ||
}) | ||
.catch(() => { | ||
setErrorMessage(Error.Add); | ||
}) | ||
.finally(() => { | ||
setWasEdited(true); | ||
}); | ||
} | ||
|
||
const handleSubmit = (event: React.ChangeEvent<HTMLFormElement>) => { | ||
event.preventDefault(); | ||
setIsSubmitted(true); | ||
|
||
const todoTitle = value.trim(); | ||
|
||
const newTodo = { | ||
id: todos.length + 1, | ||
title: todoTitle, | ||
completed: false, | ||
userId: USER_ID, | ||
}; | ||
|
||
if (!todoTitle) { | ||
setErrorMessage(Error.EmptyTitle); | ||
setIsSubmitted(false); | ||
} else { | ||
addTodo(newTodo) | ||
.then(() => setValue('')) | ||
.finally(() => { | ||
setTempTodo(null); | ||
setIsSubmitted(false); | ||
}); | ||
} | ||
}; | ||
|
||
const onDelete = (todoId: number) => { | ||
setProcessingIds((prevIds) => [...prevIds, todoId]); | ||
deleteTodo(todoId) | ||
.then(() => setTodos( | ||
currentTodos => currentTodos.filter( | ||
todo => todo.id !== todoId, | ||
), | ||
)) | ||
.catch(() => setErrorMessage(Error.Delete)) | ||
.finally(() => setProcessingIds( | ||
(prevIds) => prevIds.filter(id => id !== todoId), | ||
)); | ||
}; | ||
|
||
const onDeleteCompleted = () => { | ||
const allCompletedTodos = todos.filter(todo => todo.completed); | ||
|
||
allCompletedTodos.forEach((todo) => { | ||
onDelete(todo.id); | ||
}); | ||
}; | ||
|
||
const handleChangeCompletedStatus = ( | ||
todoId: number, | ||
isCompleted: boolean, | ||
) => { | ||
setProcessingIds(prevState => [...prevState, todoId]); | ||
|
||
return updateTodo(todoId, { completed: !isCompleted }) | ||
.then((currentTodo: Todo) => { | ||
setTodos(prevState => getUpdatedTodos( | ||
prevState, | ||
currentTodo, | ||
'completed', | ||
)); | ||
}) | ||
.catch(() => { | ||
setErrorMessage(Error.Update); | ||
}) | ||
.finally(() => { | ||
setProcessingIds(prevState => prevState | ||
.filter(id => id !== todoId)); | ||
}); | ||
}; | ||
|
||
const toggleAll = () => { | ||
const allTodosAreCompleted = todos.length === completedTodosCount.length; | ||
|
||
const todosToUpdate = allTodosAreCompleted | ||
? completedTodosCount | ||
: activeTodosCount; | ||
|
||
const promiseArray = todosToUpdate.map((todo) => { | ||
const { id, completed } = todo; | ||
const updatedCompletedStatus = !completed; | ||
|
||
return updateTodo(id, { completed: updatedCompletedStatus }); | ||
}); | ||
|
||
setIsSubmiting(true); | ||
|
||
Promise.all(promiseArray) | ||
.then(() => { | ||
setTodos(todos.map(todo => ( | ||
{ ...todo, completed: !allTodosAreCompleted } | ||
))); | ||
}) | ||
.catch(() => setErrorMessage(Error.Toggle)) | ||
.finally(() => setIsSubmiting(false)); | ||
}; | ||
|
||
const updateTodos = (todoId: number, data: Todo) => { | ||
setIsSubmitted(true); | ||
setTogglingId(todoId); | ||
|
||
updateTodo(todoId, data) | ||
.then((receivedTodo) => { | ||
setTodos((prevTodos) => prevTodos | ||
.map((todo) => (todo.id === todoId ? receivedTodo : todo))); | ||
setErrorMessage(Error.None); | ||
}) | ||
.catch(() => setErrorMessage(Error.Update)) | ||
.finally(() => { | ||
setTogglingId(null); | ||
setIsSubmitted(false); | ||
}); | ||
}; | ||
|
||
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 className="todoapp__header"> | ||
{!!todos.length && ( | ||
<button | ||
type="button" | ||
data-cy="ToggleAllButton" | ||
className={classNames('todoapp__toggle-all', { | ||
active: todos.every(todo => todo.completed), | ||
})} | ||
onClick={toggleAll} | ||
aria-label="Toggle All" | ||
/> | ||
)} | ||
|
||
<form onSubmit={handleSubmit}> | ||
<input | ||
data-cy="NewTodoField" | ||
type="text" | ||
className="todoapp__new-todo" | ||
placeholder="What needs to be done?" | ||
value={value} | ||
ref={inputRef} | ||
onChange={(event) => setValue(event.target.value)} | ||
disabled={isSubmitted} | ||
onBlur={() => setWasEdited(false)} | ||
// eslint-disable-next-line jsx-a11y/no-autofocus | ||
autoFocus | ||
/> | ||
</form> | ||
</header> | ||
|
||
{!!todos.length && ( | ||
<> | ||
<TodoList | ||
todos={visibleTodos} | ||
onDelete={onDelete} | ||
processingIds={processingIds} | ||
onToggle={handleChangeCompletedStatus} | ||
togglingId={togglingId} | ||
onUpdate={updateTodos} | ||
isSubmitted={isSubmitted} | ||
isSubmiting={isSubmiting} | ||
/> | ||
|
||
{tempTodo && ( | ||
<TodoLoadingItem | ||
tempTodo={tempTodo} | ||
isSubmitted={isSubmitted} | ||
/> | ||
)} | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
<span className="todo-count" data-cy="TodosCounter"> | ||
{getItemsLeftCountMessage(activeTodosCount)} | ||
</span> | ||
<TodoFilter | ||
todosFilterStatus={status} | ||
handleFilterStatus={setStatus} | ||
/> | ||
<button | ||
data-cy="ClearCompletedButton" | ||
type="button" | ||
className="todoapp__clear-completed" | ||
disabled={!completedTodosCount} | ||
style={{ | ||
visibility: | ||
completedTodosCount.length | ||
? 'visible' | ||
: 'hidden', | ||
}} | ||
onClick={onDeleteCompleted} | ||
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. Using inline styles is a bad practice, use css instead. |
||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
</> | ||
)} | ||
</div> | ||
|
||
<TodoError | ||
errorMessage={errorMessage} | ||
onErrorChange={() => { | ||
setErrorMessage(Error.None); | ||
}} | ||
/> | ||
</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
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,22 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { TodoUpdateData } from '../types/TodoUpdateData'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const getTodos = (userId: number) => { | ||
return client.get<Todo[]>(`/todos?userId=${userId}`); | ||
}; | ||
|
||
export const createTodo = ({ title, completed, userId }: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>('/todos', { title, completed, userId }); | ||
}; | ||
|
||
export const deleteTodo = (todoId: number) => { | ||
return client.delete(`/todos/${todoId}`); | ||
}; | ||
|
||
export const updateTodo = ( | ||
todoId: number, | ||
data: TodoUpdateData, | ||
): Promise<Todo> => { | ||
return client.patch(`/todos/${todoId}`, data); | ||
}; |
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,34 @@ | ||
import React from 'react'; | ||
import classNames from 'classnames'; | ||
import { Error } from '../../types/Error'; | ||
|
||
type Props = { | ||
errorMessage: Error, | ||
onErrorChange: () => void | ||
}; | ||
|
||
export const TodoError: React.FC<Props> = ({ errorMessage, onErrorChange }) => { | ||
return ( | ||
<div | ||
data-cy="ErrorNotification" | ||
className={classNames( | ||
'notification', | ||
'is-danger', | ||
'is-light', | ||
'has-text-weight-normal', | ||
{ | ||
hidden: !errorMessage, | ||
}, | ||
)} | ||
> | ||
<button | ||
data-cy="HideErrorButton" | ||
type="button" | ||
className="delete" | ||
onClick={onErrorChange} | ||
aria-label="Hide Error" | ||
/> | ||
{errorMessage} | ||
</div> | ||
); | ||
}; |
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.
https://upmostly.com/tutorials/settimeout-in-react-components-using-hooks
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.
Please read the article, there is an example of how to correctly work with timers in
useEffect
.