-
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 #872
Open
antonina-klishch
wants to merge
3
commits into
mate-academy:master
Choose a base branch
from
antonina-klishch: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 #872
Changes from 2 commits
Commits
Show all changes
3 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,24 +1,282 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import React, { useEffect, useMemo, useState } from 'react'; | ||
import cn from 'classnames'; | ||
import * as todoService from './api/todos'; | ||
import { UserWarning } from './UserWarning'; | ||
|
||
const USER_ID = 0; | ||
import { Header } from './components/Header'; | ||
import { Footer } from './components/Footer'; | ||
import { TodoList } from './components/TodoList'; | ||
import { Todo } from './types/Todo'; | ||
import { getTodos } from './api/todos'; | ||
import { USER_ID } from './utils/fetchClient'; | ||
import { Status } from './types/Status'; | ||
import { Message } from './types/Message'; | ||
import { ErrorNotification } from './components/ErrorNotification'; | ||
|
||
export const App: React.FC = () => { | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [todosStatus, setTodosStatus] = useState<Status>(Status.All); | ||
const [isLoading, setIsLoading] = useState(false); | ||
const [errorMessage, setErrorMessage] = useState<Message | ''>(''); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [titleTodo, setTitleTodo] = useState(''); | ||
const [deletedTodo, setDeletedTodo] = useState<number[]>([]); | ||
const [changedTodo, setChangedTodo] = useState<number[]>([]); | ||
|
||
const filterTodos = (listTodos: Todo[], status: Status) => { | ||
switch (status) { | ||
case Status.Active: | ||
return listTodos.filter(todo => !todo.completed); | ||
case Status.Completed: | ||
return listTodos.filter(todo => todo.completed); | ||
case Status.All: | ||
default: | ||
return listTodos; | ||
} | ||
}; | ||
|
||
const addTodo = ({ userId, title, completed }: Todo) => { | ||
setErrorMessage(''); | ||
setIsLoading(true); | ||
|
||
const createdTodo = { | ||
id: 0, | ||
userId: USER_ID, | ||
title: title.trim(), | ||
completed: false, | ||
}; | ||
|
||
setTempTodo(createdTodo); | ||
|
||
todoService.createTodo({ userId, title, completed }) | ||
.then(newTodo => { | ||
setTodos(currentTodos => [...currentTodos, newTodo]); | ||
setTitleTodo(''); | ||
}) | ||
.catch(() => { | ||
setErrorMessage(Message.NoAddTodo); | ||
}) | ||
.finally(() => { | ||
setIsLoading(false); | ||
setTempTodo(null); | ||
}); | ||
}; | ||
|
||
const removeCompletedTodos = (todosId: number[]) => { | ||
setIsLoading(true); | ||
setDeletedTodo(todosId); | ||
|
||
todosId.map(todoId => { | ||
return todoService.deleteTodos(todoId) | ||
.then(() => { | ||
setTodos(currentTodos => ( | ||
currentTodos.filter(todo => todo.id !== todoId) | ||
)); | ||
}) | ||
.catch((error) => { | ||
setDeletedTodo([]); | ||
setErrorMessage(Message.NoDeleteTodo); | ||
throw error; | ||
}) | ||
.finally(() => { | ||
setDeletedTodo([]); | ||
setIsLoading(false); | ||
}); | ||
}); | ||
}; | ||
|
||
const updateTodoStatus = (updatedTodo: Todo) => { | ||
setErrorMessage(''); | ||
setIsLoading(true); | ||
setChangedTodo([updatedTodo.id]); | ||
|
||
return todoService.updateTodo(updatedTodo) | ||
.then(() => { | ||
setTodos(todos.map(todo => ( | ||
todo.id === updatedTodo.id | ||
? { | ||
...todo, | ||
completed: updatedTodo.completed, | ||
|
||
} | ||
: todo | ||
))); | ||
}) | ||
.catch(() => setErrorMessage(Message.NoUpdateTodo)) | ||
.finally(() => { | ||
setIsLoading(false); | ||
setChangedTodo([]); | ||
}); | ||
}; | ||
|
||
const updateTodo = async (todo: Todo) => { | ||
try { | ||
const newTodo = await todoService.updateTodo(todo); | ||
|
||
return newTodo; | ||
} catch (error) { | ||
setErrorMessage(Message.NoUpdateTodo); | ||
|
||
return todo; | ||
} | ||
}; | ||
|
||
const updateTodosAllStatus = (updatedTodos: Todo[]) => { | ||
setErrorMessage(''); | ||
setIsLoading(true); | ||
const changedTodoIds = updatedTodos.map(todo => todo.id); | ||
|
||
setChangedTodo(changedTodoIds); | ||
|
||
Promise.all(updatedTodos.map(updatedTodo => updateTodo(updatedTodo))) | ||
.then((gettedTodos) => { | ||
const gettedTodosId = gettedTodos.map(todo => todo.id); | ||
|
||
setTodos(currentTodos => currentTodos.map( | ||
todo => ( | ||
gettedTodosId.includes(todo.id) | ||
? { ...todo, completed: gettedTodos[0].completed } | ||
: todo | ||
), | ||
)); | ||
}) | ||
.finally(() => { | ||
setIsLoading(false); | ||
setChangedTodo([]); | ||
}); | ||
}; | ||
|
||
const updateTitleTodo = (updatedTodo: Todo) => { | ||
setErrorMessage(''); | ||
setChangedTodo([updatedTodo.id]); | ||
|
||
setTodos(todos.map(todo => ( | ||
todo.id === updatedTodo.id | ||
? { | ||
...todo, | ||
title: updatedTodo.title, | ||
} | ||
: todo | ||
))); | ||
|
||
return todoService.updateTodo(updatedTodo) | ||
.catch((error) => { | ||
setErrorMessage(Message.NoUpdateTodo); | ||
throw error; | ||
}) | ||
.finally(() => { | ||
setChangedTodo([]); | ||
}); | ||
}; | ||
|
||
const removeTodoTitle = (todoId: number) => { | ||
setDeletedTodo([todoId]); | ||
|
||
return todoService.deleteTodos(todoId) | ||
.then(() => { | ||
setTodos(currentTodos => ( | ||
currentTodos.filter(todo => todo.id !== todoId) | ||
)); | ||
}) | ||
.catch((error) => { | ||
setTodos(todos); | ||
setErrorMessage(Message.NoDeleteTodo); | ||
throw error; | ||
}) | ||
.finally(() => { | ||
setDeletedTodo([]); | ||
}); | ||
}; | ||
|
||
const visibleTodos = useMemo(() => filterTodos(todos, todosStatus), | ||
[todos, todosStatus]); | ||
const activeTodos = useMemo(() => todos.filter(todo => !todo.completed), | ||
[todos]); | ||
|
||
useEffect(() => { | ||
getTodos(USER_ID) | ||
.then(setTodos) | ||
.catch(() => setErrorMessage(Message.NoLoadTotos)); | ||
}, []); | ||
|
||
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 | ||
setTitleTodo={setTitleTodo} | ||
titleTodo={titleTodo} | ||
setErrorMessage={setErrorMessage} | ||
onAddTodo={addTodo} | ||
isLoading={isLoading} | ||
setTodos={setTodos} | ||
todos={todos} | ||
updateTodosAllStatus={updateTodosAllStatus} | ||
/> | ||
|
||
{todos.length > 0 && ( | ||
<TodoList | ||
todos={visibleTodos} | ||
removeCompletedTodos={removeCompletedTodos} | ||
removeTodoTitle={removeTodoTitle} | ||
deletedTodo={deletedTodo} | ||
updateTodoStatus={updateTodoStatus} | ||
changedTodo={changedTodo} | ||
updateTitleTodo={updateTitleTodo} | ||
/> | ||
)} | ||
{tempTodo && ( | ||
<div data-cy="Todo" className="todo"> | ||
<label className="todo__status-label"> | ||
<input | ||
data-cy="TodoStatus" | ||
type="checkbox" | ||
className="todo__status" | ||
/> | ||
</label> | ||
<> | ||
<span data-cy="TodoTitle" className="todo__title"> | ||
{tempTodo.title} | ||
</span> | ||
<button | ||
type="button" | ||
className="todo__remove" | ||
data-cy="TodoDelete" | ||
> | ||
× | ||
</button> | ||
</> | ||
<div | ||
data-cy="TodoLoader" | ||
className={cn('modal overlay', { | ||
'is-active': tempTodo.id === 0, | ||
})} | ||
> | ||
<div className="modal-background has-background-white-ter" /> | ||
<div className="loader" /> | ||
</div> | ||
</div> | ||
)} | ||
{(todos.length > 0 || tempTodo) && ( | ||
<Footer | ||
todosStatus={todosStatus} | ||
setTodosStatus={setTodosStatus} | ||
todos={visibleTodos} | ||
activeTodos={activeTodos} | ||
removeTodo={removeCompletedTodos} | ||
/> | ||
)} | ||
</div> | ||
|
||
<ErrorNotification | ||
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,20 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const getTodos = (userId: number) => { | ||
return client.get<Todo[]>(`/todos?userId=${userId}`); | ||
}; | ||
|
||
export const deleteTodos = (todoId: number) => { | ||
return client.delete(`/todos/${todoId}`); | ||
}; | ||
|
||
export const createTodo = ({ userId, title, completed }: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>('/todos', { userId, title, completed }); | ||
}; | ||
|
||
export const updateTodo = ({ | ||
id, userId, title, completed, | ||
}: Todo) => { | ||
return client.patch<Todo>(`/todos/${id}`, { userId, title, completed }); | ||
}; |
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,35 @@ | ||
import React from 'react'; | ||
import cn from 'classnames'; | ||
import { Message } from '../../types/Message'; | ||
|
||
type Props = { | ||
errorMessage: Message | '', | ||
setErrorMessage: (m: Message | '') => void, | ||
}; | ||
|
||
export const ErrorNotification: React.FC<Props> = React.memo(({ | ||
errorMessage, | ||
setErrorMessage, | ||
}) => { | ||
setTimeout(() => { | ||
setErrorMessage(''); | ||
}, 3000); | ||
|
||
return ( | ||
<div | ||
data-cy="ErrorNotification" | ||
className={cn('notification is-danger is-light has-text-weight-normal', { | ||
hidden: !errorMessage, | ||
})} | ||
> | ||
<button | ||
aria-label="Close message" | ||
data-cy="HideErrorButton" | ||
type="button" | ||
className="delete" | ||
onClick={() => setErrorMessage('')} | ||
/> | ||
{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 './ErrorNotification'; |
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.
please memoize all functions what you passing to the child components
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.
pay attention to this comment, use useMemo or useCallback for this purpose, it will optimize your code