-
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
Initital solution #1493
Open
v1RnT
wants to merge
2
commits into
mate-academy:master
Choose a base branch
from
v1RnT: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
Initital solution #1493
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 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,170 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
import React, { useCallback, useEffect, useMemo, useState } from 'react'; | ||
import { deleteTodo, getTodos, patchTodo } from './api/todos'; | ||
|
||
const USER_ID = 0; | ||
import { Todo } from './types/Todo'; | ||
import { Filter } from './types/Filter'; | ||
import { Errors } from './types/Errors'; | ||
|
||
import { Footer } from './components/Footer'; | ||
import { Header } from './components/Header'; | ||
import { TodoList } from './components/TodoList'; | ||
import { ErrorMessage } from './components/ErrorMessage'; | ||
|
||
import { handleError } from './utils/handleError'; | ||
import { getFilteredTodos } from './utils/getFilteredTodos'; | ||
|
||
export const App: React.FC = () => { | ||
if (!USER_ID) { | ||
return <UserWarning />; | ||
} | ||
const [todosFromServer, setTodosFromServer] = useState<Todo[]>([]); | ||
const [errorMessage, setErrorMessage] = useState<Errors>(Errors.Default); | ||
const [filterOption, setFilterOption] = useState<Filter>(Filter.All); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [deletionIds, setDeletionIds] = useState<number[]>([]); | ||
const [pendingTodos, setPendingTodos] = useState<Todo[]>([]); | ||
|
||
const completedTodoIds = useMemo(() => { | ||
return todosFromServer.filter(todo => todo.completed).map(todo => todo.id); | ||
}, [todosFromServer]); | ||
|
||
const uncompletedTodos = useMemo(() => { | ||
return todosFromServer.filter(todo => !todo.completed); | ||
}, [todosFromServer]); | ||
|
||
const uncompletedTodosAmount = uncompletedTodos.length; | ||
|
||
const filteredTodos = useMemo(() => { | ||
return getFilteredTodos(todosFromServer, filterOption); | ||
}, [todosFromServer, filterOption]); | ||
|
||
const handleDeleteTodos = useCallback((ids: number[]) => { | ||
Promise.all( | ||
ids.map(id => { | ||
setDeletionIds(current => [...current, id]); | ||
|
||
deleteTodo(id) | ||
.then(() => { | ||
setTodosFromServer(current => | ||
current.filter(todo => todo.id !== id), | ||
); | ||
}) | ||
.catch(() => { | ||
handleError(setErrorMessage, Errors.DeleteTodo); | ||
}) | ||
.finally(() => | ||
setDeletionIds(currIds => currIds.filter(currId => currId !== id)), | ||
); | ||
}), | ||
); | ||
}, []); | ||
|
||
const handleChangeTodos = useCallback( | ||
(newTodos: Todo[]) => { | ||
return Promise.all( | ||
newTodos.map(todo => { | ||
setPendingTodos(current => [...current, todo]); | ||
|
||
const { id, ...todoBody } = todo; | ||
|
||
return patchTodo(todoBody, id) | ||
.then(() => { | ||
setTodosFromServer(current => | ||
current.map(currentTodo => { | ||
return currentTodo.id !== todo.id ? currentTodo : todo; | ||
}), | ||
); | ||
}) | ||
.catch(() => { | ||
handleError(setErrorMessage, Errors.UpdateTodo); | ||
throw new Error(errorMessage); | ||
}) | ||
.finally(() => setPendingTodos([])); | ||
}), | ||
); | ||
}, | ||
[errorMessage], | ||
); | ||
|
||
const handleToggleCompleted = (id: number, updatedField: Partial<Todo>) => { | ||
setPendingTodos(current => [...current]); | ||
|
||
return patchTodo(updatedField, id) | ||
.then((updatedTodo: Todo) => | ||
setTodosFromServer(current => | ||
current.map(todo => (todo.id === id ? updatedTodo : todo)), | ||
), | ||
) | ||
.catch(() => { | ||
handleError(setErrorMessage, Errors.UpdateTodo); | ||
throw new Error(errorMessage); | ||
}) | ||
.finally(() => | ||
setPendingTodos(current => current.filter(todo => todo.id !== id)), | ||
); | ||
}; | ||
|
||
const handleToggleCompletedAll = () => { | ||
if (uncompletedTodos && uncompletedTodosAmount) { | ||
Promise.allSettled( | ||
uncompletedTodos.map(({ id }) => | ||
handleToggleCompleted(id, { completed: true }), | ||
), | ||
); | ||
} else { | ||
Promise.allSettled( | ||
todosFromServer.map(({ id }) => | ||
handleToggleCompleted(id, { completed: false }), | ||
), | ||
); | ||
} | ||
}; | ||
|
||
useEffect(() => { | ||
getTodos() | ||
.then(setTodosFromServer) | ||
.catch(() => handleError(setErrorMessage, Errors.LoadingTodos)); | ||
}, []); | ||
|
||
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 | ||
setTodos={setTodosFromServer} | ||
setError={setErrorMessage} | ||
setTempTodo={setTempTodo} | ||
tempTodo={tempTodo} | ||
uncompletedTodosAmount={uncompletedTodosAmount} | ||
todos={todosFromServer} | ||
onToggleCompletedAll={handleToggleCompletedAll} | ||
/> | ||
|
||
{!!todosFromServer.length && ( | ||
<> | ||
<TodoList | ||
todos={filteredTodos} | ||
tempTodo={tempTodo} | ||
deletionIds={deletionIds} | ||
pendingTodos={pendingTodos} | ||
errorMessage={errorMessage} | ||
onTodosChange={handleChangeTodos} | ||
onDeleteTodos={handleDeleteTodos} | ||
/> | ||
<Footer | ||
filterOption={filterOption} | ||
completedTodoIds={completedTodoIds} | ||
uncompletedTodosAmount={uncompletedTodosAmount} | ||
setFilterOption={setFilterOption} | ||
setDeletionIds={setDeletionIds} | ||
onDeleteTodos={handleDeleteTodos} | ||
/> | ||
</> | ||
)} | ||
</div> | ||
|
||
<ErrorMessage | ||
errorMessage={errorMessage} | ||
setErrorMessage={setErrorMessage} | ||
/> | ||
</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,16 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const USER_ID = 1606; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const postTodo = (todo: Omit<Todo, 'id'>): Promise<Todo> => | ||
client.post<Todo>('/todos', todo); | ||
|
||
export const deleteTodo = (todoId: number) => client.delete(`/todos/${todoId}`); | ||
|
||
export const patchTodo = (props: Partial<Todo>, id: number): Promise<Todo> => | ||
client.patch<Todo>(`/todos/${id}`, props); |
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,28 @@ | ||
import { FC, Dispatch } from 'react'; | ||
import cn from 'classnames'; | ||
import { Errors } from '../../types/Errors'; | ||
|
||
type Props = { | ||
errorMessage: Errors; | ||
setErrorMessage: Dispatch<React.SetStateAction<Errors>>; | ||
}; | ||
|
||
export const ErrorMessage: FC<Props> = ({ errorMessage, setErrorMessage }) => { | ||
return ( | ||
<div | ||
data-cy="ErrorNotification" | ||
// eslint-disable-next-line max-len | ||
className={cn('notification is-danger is-light has-text-weight-normal', { | ||
hidden: !errorMessage, | ||
})} | ||
> | ||
<button | ||
data-cy="HideErrorButton" | ||
type="button" | ||
className={cn('delete', { hidden: !errorMessage })} | ||
onClick={() => setErrorMessage(Errors.Default)} | ||
/> | ||
{errorMessage} | ||
</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 @@ | ||
export * from './ErrorMessage'; |
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,56 @@ | ||
import { FC, Dispatch, SetStateAction } from 'react'; | ||
import { Filter } from '../../types/Filter'; | ||
import cn from 'classnames'; | ||
|
||
type Props = { | ||
completedTodoIds: number[]; | ||
uncompletedTodosAmount: number; | ||
filterOption: Filter; | ||
setFilterOption: Dispatch<SetStateAction<Filter>>; | ||
setDeletionIds: Dispatch<SetStateAction<number[]>>; | ||
onDeleteTodos: (ids: number[]) => void; | ||
}; | ||
|
||
export const Footer: FC<Props> = ({ | ||
completedTodoIds, | ||
uncompletedTodosAmount, | ||
filterOption, | ||
setFilterOption, | ||
onDeleteTodos, | ||
}) => { | ||
return ( | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
<span className="todo-count" data-cy="TodosCounter"> | ||
{uncompletedTodosAmount} items left | ||
</span> | ||
|
||
<nav className="filter" data-cy="Filter"> | ||
{Object.values(Filter).map(filter => { | ||
return ( | ||
<a | ||
href={filter === 'All' ? '#/' : `#/${filter.toLowerCase()}`} | ||
className={cn('filter__link', { | ||
selected: filter === filterOption, | ||
})} | ||
data-cy={`FilterLink${filter}`} | ||
key={filter} | ||
onClick={() => setFilterOption(filter)} | ||
> | ||
{filter} | ||
</a> | ||
); | ||
})} | ||
</nav> | ||
|
||
<button | ||
type="button" | ||
className="todoapp__clear-completed" | ||
data-cy="ClearCompletedButton" | ||
onClick={() => onDeleteTodos(completedTodoIds)} | ||
disabled={!completedTodoIds.length} | ||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
); | ||
}; |
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 @@ | ||
export * from './Footer'; |
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,96 @@ | ||
import { | ||
FC, | ||
Dispatch, | ||
SetStateAction, | ||
useRef, | ||
useEffect, | ||
useState, | ||
} from 'react'; | ||
import cn from 'classnames'; | ||
import { InputForm } from '../InputForm'; | ||
import { Todo } from '../../types/Todo'; | ||
import { Errors } from '../../types/Errors'; | ||
import { handleError } from '../../utils/handleError'; | ||
import { postTodo, USER_ID } from '../../api/todos'; | ||
|
||
type Props = { | ||
todos: Todo[]; | ||
tempTodo: Todo | null; | ||
uncompletedTodosAmount: number; | ||
setTempTodo: Dispatch<SetStateAction<Todo | null>>; | ||
setError: Dispatch<SetStateAction<Errors>>; | ||
setTodos: Dispatch<SetStateAction<Todo[]>>; | ||
onToggleCompletedAll: () => void; | ||
}; | ||
|
||
export const Header: FC<Props> = ({ | ||
todos, | ||
tempTodo, | ||
uncompletedTodosAmount, | ||
setTempTodo, | ||
setError, | ||
setTodos, | ||
onToggleCompletedAll, | ||
}) => { | ||
const [inputValue, setInputValue] = useState(''); | ||
const inputRef = useRef<HTMLInputElement | null>(null); | ||
|
||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { | ||
event.preventDefault(); | ||
|
||
const trimmedInputValues = inputValue.trim(); | ||
|
||
if (!trimmedInputValues) { | ||
handleError(setError, Errors.EmptyTitle); | ||
|
||
return; | ||
} | ||
|
||
const temporaryTodo: Todo = { | ||
id: 0, | ||
userId: USER_ID, | ||
title: trimmedInputValues, | ||
completed: false, | ||
}; | ||
|
||
setTempTodo(temporaryTodo); | ||
|
||
postTodo(temporaryTodo) | ||
.then(res => { | ||
setTodos(current => [...current, res]); | ||
setInputValue(''); | ||
setTempTodo(null); | ||
}) | ||
.catch(() => { | ||
setTempTodo(null); | ||
handleError(setError, Errors.AddTodo); | ||
}); | ||
}; | ||
|
||
useEffect(() => { | ||
inputRef.current?.focus(); | ||
}, [todos, tempTodo]); | ||
|
||
return ( | ||
<header className="todoapp__header"> | ||
{!!todos.length && ( | ||
<button | ||
type="button" | ||
className={cn('todoapp__toggle-all', { | ||
active: uncompletedTodosAmount === 0, | ||
})} | ||
data-cy="ToggleAllButton" | ||
onClick={onToggleCompletedAll} | ||
/> | ||
)} | ||
|
||
<InputForm | ||
handleSubmit={handleSubmit} | ||
inputRef={inputRef} | ||
tempTodo={tempTodo} | ||
inputValue={inputValue} | ||
setInputValue={setInputValue} | ||
/> | ||
</header> | ||
); | ||
}; |
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.
It's better to move the logic inside the
useEffect
hook to a separate function, as it improves code readability, reusability, and makes testing easier. It also helps keepuseEffect
focused on side effects.