-
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
finnish #1492
base: master
Are you sure you want to change the base?
finnish #1492
Changes from all commits
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,289 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
import React, { | ||
ChangeEvent, | ||
useCallback, | ||
useEffect, | ||
useMemo, | ||
useRef, | ||
useState, | ||
} from 'react'; | ||
|
||
const USER_ID = 0; | ||
import { UserWarning } from './UserWarning'; | ||
import { | ||
USER_ID, | ||
deleteTodo, | ||
getTodos, | ||
updateTodo, | ||
uploadTodo, | ||
} from './api/todos'; | ||
import { Todo } from './types/Todo'; | ||
import { TodoStatus } from './types/TodoStatus'; | ||
import { ErrorType } from './types/Errors'; | ||
import { Header } from './components/Header'; | ||
import { TodoList } from './components/TodoList'; | ||
import { Footer } from './components/Footer'; | ||
import { emptyTodo } from './utils/EmptyTodo'; | ||
import { UpdateTodoData } from './types/UpdateTodoData'; | ||
import { ErrorNotification } from './components/ErrorNoti/ErrorNotiflication'; | ||
|
||
export const App: React.FC = () => { | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [todoTitle, setTodoTitle] = useState(''); | ||
const [isLoading, setIsLoading] = useState(false); | ||
const [selectedTodoStatus, setSelectedTodoStatus] = useState(TodoStatus.All); | ||
const [errorMessage, setErrorMessage] = useState<ErrorType | ''>(''); | ||
const [processingTodos, setProcessingTodos] = useState<number[]>([]); | ||
const [editingTodoId, setEditingTodoId] = useState<number | null>(null); | ||
|
||
const inputRef = useRef<HTMLInputElement | null>(null); | ||
|
||
const focusInputField = () => inputRef.current?.focus(); | ||
|
||
useEffect(() => { | ||
getTodos() | ||
.then(setTodos) | ||
.catch(() => setErrorMessage(ErrorType.LOAD_TODOS)); | ||
Comment on lines
+42
to
+44
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. Move the |
||
}, []); | ||
|
||
useEffect(() => { | ||
const timer = setTimeout(() => setErrorMessage(''), 3000); | ||
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. 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 keep useEffect focused on side effects. 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. Good point! |
||
|
||
return () => clearTimeout(timer); | ||
}, [errorMessage]); | ||
|
||
useEffect(focusInputField, [todoTitle, todos, selectedTodoStatus, isLoading]); | ||
|
||
const filteringTodosByActiveStatus = useMemo( | ||
() => todos.filter(todo => !todo.completed), | ||
[todos], | ||
); | ||
|
||
const filteringTodosByCompletedStatus = useMemo( | ||
() => todos.filter(todo => todo.completed), | ||
[todos], | ||
); | ||
|
||
const filteredTodos = useMemo(() => { | ||
switch (selectedTodoStatus) { | ||
case TodoStatus.Active: | ||
return filteringTodosByActiveStatus; | ||
|
||
case TodoStatus.Completed: | ||
return filteringTodosByCompletedStatus; | ||
|
||
default: | ||
return todos; | ||
} | ||
}, [ | ||
filteringTodosByActiveStatus, | ||
filteringTodosByCompletedStatus, | ||
selectedTodoStatus, | ||
todos, | ||
]); | ||
|
||
const changeTodoTitleHandler = useCallback( | ||
(e: ChangeEvent<HTMLInputElement>) => { | ||
setErrorMessage(''); | ||
setTodoTitle(e.target.value); | ||
}, | ||
[], | ||
); | ||
|
||
const closeErrorHandler = () => setErrorMessage(''); | ||
|
||
const handleStatusChange = (status: TodoStatus) => | ||
setSelectedTodoStatus(status); | ||
|
||
const selectedEditTodoId = (id: number | null) => setEditingTodoId(id); | ||
|
||
const updateProcessingTodos = (id: number) => | ||
setProcessingTodos(prev => [...prev, id]); | ||
|
||
const removeProcessingTodos = (id: number) => | ||
setProcessingTodos(prev => prev.filter(prevItem => prevItem !== id)); | ||
|
||
const addTodo = useCallback( | ||
async (e: React.FormEvent<HTMLFormElement>) => { | ||
e.preventDefault(); | ||
if (!todoTitle.trim()) { | ||
setErrorMessage(ErrorType.EMPTY_TITLE); | ||
|
||
return; | ||
} | ||
|
||
setIsLoading(true); | ||
setErrorMessage(''); | ||
const newTempTodo: Todo = { ...emptyTodo, title: todoTitle.trim() }; | ||
|
||
setTempTodo(newTempTodo); | ||
setProcessingTodos([newTempTodo.id]); | ||
|
||
try { | ||
const todo = await uploadTodo({ | ||
...emptyTodo, | ||
title: todoTitle.trim(), | ||
}); | ||
|
||
setTodos(currentTodos => [...currentTodos, todo]); | ||
setTodoTitle(''); | ||
} catch { | ||
setErrorMessage(ErrorType.ADD_TODO); | ||
} finally { | ||
setIsLoading(false); | ||
setTempTodo(null); | ||
setProcessingTodos([]); | ||
focusInputField(); | ||
} | ||
}, | ||
[todoTitle], | ||
); | ||
|
||
const onDeleteTodo = useCallback((id: number) => { | ||
deleteTodo(id) | ||
.then(() => | ||
setTodos(currentTodos => currentTodos.filter(todo => todo.id !== id)), | ||
) | ||
.catch(() => setErrorMessage(ErrorType.DELETE_TODO)) | ||
.finally(() => { | ||
removeProcessingTodos(id); | ||
focusInputField(); | ||
}); | ||
}, []); | ||
|
||
const removeTodo = useCallback( | ||
(id: number) => { | ||
setErrorMessage(''); | ||
updateProcessingTodos(id); | ||
onDeleteTodo(id); | ||
}, | ||
[onDeleteTodo], | ||
); | ||
|
||
const removeTodos = useCallback(async () => { | ||
setIsLoading(true); | ||
setErrorMessage(''); | ||
|
||
const deletePromises = filteringTodosByCompletedStatus.map(todo => | ||
removeTodo(todo.id), | ||
); | ||
|
||
await Promise.allSettled(deletePromises); | ||
setIsLoading(false); | ||
}, [filteringTodosByCompletedStatus, removeTodo]); | ||
|
||
const onUpdateTodo = useCallback(async (id: number, data: UpdateTodoData) => { | ||
return updateTodo(id, data) | ||
.then(todo => { | ||
setTodos(currentTodos => { | ||
const newTodos = [...currentTodos]; | ||
const index = newTodos.findIndex( | ||
findedTodo => findedTodo.id === todo.id, | ||
); | ||
|
||
newTodos.splice(index, 1, todo); | ||
|
||
return newTodos; | ||
}); | ||
setEditingTodoId(null); | ||
}) | ||
.catch(() => { | ||
setErrorMessage(ErrorType.UPDATE_TODO); | ||
if ('title' in data) { | ||
setEditingTodoId(id); | ||
throw new Error(); | ||
} | ||
}) | ||
.finally(() => { | ||
removeProcessingTodos(id); | ||
if (!('title' in data)) { | ||
focusInputField(); | ||
} | ||
}); | ||
}, []); | ||
|
||
const toggleTodoStatus = useCallback( | ||
(id: number, data: UpdateTodoData) => { | ||
setErrorMessage(''); | ||
updateProcessingTodos(id); | ||
onUpdateTodo(id, data); | ||
}, | ||
[onUpdateTodo], | ||
); | ||
|
||
const toggleAll = useCallback(async () => { | ||
setIsLoading(true); | ||
setErrorMessage(''); | ||
|
||
let todosForChange: Todo[] = []; | ||
|
||
if (filteringTodosByCompletedStatus.length !== todos.length) { | ||
todosForChange = [...filteringTodosByActiveStatus]; | ||
} else { | ||
todosForChange = [...todos]; | ||
} | ||
|
||
const togglePromises = todosForChange.map(todo => | ||
toggleTodoStatus(todo.id, { completed: !todo.completed }), | ||
); | ||
|
||
await Promise.allSettled(togglePromises); | ||
setIsLoading(false); | ||
}, [ | ||
filteringTodosByActiveStatus, | ||
filteringTodosByCompletedStatus.length, | ||
todos, | ||
toggleTodoStatus, | ||
]); | ||
|
||
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} | ||
value={todoTitle} | ||
addTodo={addTodo} | ||
onChange={changeTodoTitleHandler} | ||
inputRef={inputRef} | ||
isLoading={isLoading} | ||
completedTodosCount={filteringTodosByCompletedStatus.length} | ||
toggleAll={toggleAll} | ||
/> | ||
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. Use |
||
<TodoList | ||
preparedTodos={filteredTodos} | ||
processingTodos={processingTodos} | ||
tempTodo={tempTodo} | ||
removeTodo={removeTodo} | ||
toggleTodoStatus={toggleTodoStatus} | ||
errorMessage={errorMessage} | ||
editingTodoId={editingTodoId} | ||
selectedEditTodoId={selectedEditTodoId} | ||
onUpdateTodo={onUpdateTodo} | ||
updateProcessingTodos={updateProcessingTodos} | ||
removeProcessingTodos={removeProcessingTodos} | ||
/> | ||
|
||
<Footer | ||
todos={todos} | ||
selectedStatus={selectedTodoStatus} | ||
onStatusChange={handleStatusChange} | ||
filteringTodosByActiveStatus={filteringTodosByActiveStatus.length} | ||
filteringTodosByCompletedStatus={ | ||
filteringTodosByCompletedStatus.length | ||
} | ||
removeTodos={removeTodos} | ||
/> | ||
</div> | ||
|
||
<ErrorNotification | ||
errorMessage={errorMessage} | ||
closeErrorHandler={closeErrorHandler} | ||
/> | ||
</div> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
import { UpdateTodoData } from '../types/UpdateTodoData'; | ||
|
||
export const USER_ID = 337; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const uploadTodo = ({ completed, title, userId }: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>('/todos', { completed, title, userId }); | ||
}; | ||
|
||
export const deleteTodo = (id: number) => { | ||
return client.delete(`/todos/${id}`); | ||
}; | ||
|
||
export const updateTodo = (id: number, data: UpdateTodoData) => { | ||
return client.patch<Todo>(`/todos/${id}`, data); | ||
}; |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,29 @@ | ||||||
import classNames from 'classnames'; | ||||||
|
||||||
type Props = { | ||||||
errorMessage: string; | ||||||
closeErrorHandler: () => void; | ||||||
}; | ||||||
|
||||||
export const ErrorNotification: React.FC<Props> = ({ | ||||||
errorMessage, | ||||||
closeErrorHandler, | ||||||
}) => { | ||||||
return ( | ||||||
<div | ||||||
data-cy="ErrorNotification" | ||||||
className={classNames( | ||||||
'notification is-danger is-light has-text-weight-normal', | ||||||
{ hidden: errorMessage.length === 0 }, | ||||||
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.
Suggested change
|
||||||
)} | ||||||
> | ||||||
<button | ||||||
data-cy="HideErrorButton" | ||||||
type="button" | ||||||
className="delete" | ||||||
onClick={closeErrorHandler} | ||||||
/> | ||||||
{errorMessage} | ||||||
</div> | ||||||
); | ||||||
}; |
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.
Create an
DEFAULT
value in enum and us it