-
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 #548
base: master
Are you sure you want to change the base?
Solution #548
Changes from 3 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,24 +1,245 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import React, { | ||
useState, | ||
useEffect, | ||
useCallback, | ||
useMemo, | ||
} from 'react'; | ||
import { v4 as uuidv4 } from 'uuid'; | ||
import { UserWarning } from './UserWarning'; | ||
import { TodoHeader } from './components/TodoHeader/TodoHeader'; | ||
import { TodoList } from './components/TodoList/TodoList'; | ||
import { TodoFooter } from './components/TodoFooter/TodoFooter'; | ||
import { TodoNotification } from './components/TodoNotification'; | ||
import { | ||
getTodos, | ||
createTodo, | ||
updateTodo, | ||
deleteTodo, | ||
} from './api/todos'; | ||
import { TodoStatus } from './types/TodoStatus'; | ||
import { Todo } from './types/Todo'; | ||
import { TodoListContext } from './context/TodoListContext'; | ||
|
||
const USER_ID = 0; | ||
const USER_ID = 10509; | ||
|
||
export const App: React.FC = () => { | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [filterBy, setFilterBy] = useState(TodoStatus.All); | ||
const [hasError, setHasError] = useState(false); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [errorMessage, setErrorMessage] = useState(''); | ||
const [completedTodoIdList, setCompletedTodoIdList] = useState<number[]>([]); | ||
|
||
const showErrorMessage = (message: string) => { | ||
setHasError(true); | ||
setErrorMessage(message); | ||
}; | ||
|
||
const handleCloseButton = useCallback(() => { | ||
setHasError(!hasError); | ||
}, [hasError]); | ||
|
||
const visibleTodos = useMemo(() => { | ||
return todos.filter(todo => { | ||
if (filterBy === TodoStatus.Active) { | ||
return !todo.completed; | ||
} | ||
|
||
if (filterBy === TodoStatus.Completed) { | ||
return todo.completed; | ||
} | ||
|
||
return true; | ||
}); | ||
}, [todos, filterBy]); | ||
|
||
const activeTodosCount = useMemo(() => ( | ||
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. The dependency array for this useMemo should include 'todos' instead of 'visibleTodos'. |
||
todos.filter(todo => !todo.completed).length | ||
), [todos]); | ||
|
||
const areAllTodosCompleted = useMemo(() => ( | ||
todos.every(todo => todo.completed) | ||
), [todos]); | ||
|
||
const toggleAllTodos = useCallback(async () => { | ||
const todosToToggle = areAllTodosCompleted | ||
? todos.filter(todo => todo.completed) | ||
: todos.filter(todo => !todo.completed); | ||
|
||
setCompletedTodoIdList(todosToToggle.map(todo => todo.id)); | ||
|
||
try { | ||
const updatedTodos = await Promise.all(todosToToggle | ||
.map(todo => updateTodo(todo.id, { completed: !todo.completed }))); | ||
|
||
setTodos(currTodos => currTodos.map(todo => { | ||
const updatedTodo = updatedTodos.find(task => task.id === todo.id); | ||
|
||
return updatedTodo || todo; | ||
})); | ||
} catch { | ||
showErrorMessage('Unable to update the todos'); | ||
} finally { | ||
setCompletedTodoIdList([]); | ||
} | ||
}, [todos]); | ||
|
||
const handleEnterKeyPress = useCallback((title: string) => { | ||
setTempTodo({ | ||
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 use a unique identifier for the todo id instead of using Math.random(). As a variant, consider installing and using a library like 'uuid' to generate unique ids |
||
id: parseInt(uuidv4(), 16), | ||
userId: USER_ID, | ||
title, | ||
completed: false, | ||
}); | ||
|
||
createTodo({ | ||
userId: USER_ID, | ||
title, | ||
completed: false, | ||
}) | ||
.then(fetchedTodo => setTodos(currTodos => [...currTodos, fetchedTodo])) | ||
.catch(() => showErrorMessage('Unable to add a todo')) | ||
.finally(() => setTempTodo(null)); | ||
}, []); | ||
|
||
const handleToggleButtonClick = useCallback(async ( | ||
todoId: number, | ||
completed: boolean, | ||
) => { | ||
setCompletedTodoIdList([todoId]); | ||
|
||
try { | ||
const updatedTodo = await updateTodo(todoId, { completed: !completed }); | ||
|
||
setTodos(currTodos => currTodos.map(todo => { | ||
return todo.id === todoId | ||
? updatedTodo | ||
: todo; | ||
})); | ||
} catch { | ||
showErrorMessage('Unable to update a todo'); | ||
} finally { | ||
setCompletedTodoIdList([]); | ||
} | ||
}, [todos]); | ||
|
||
const handleTodoRename = useCallback(async ( | ||
todoId: number, | ||
title: string, | ||
) => { | ||
setCompletedTodoIdList([todoId]); | ||
|
||
try { | ||
const updatedTodo = await updateTodo(todoId, { title }); | ||
|
||
setTodos(currTodos => currTodos.map(todo => { | ||
return todo.id === todoId | ||
? updatedTodo | ||
: todo; | ||
})); | ||
} catch { | ||
showErrorMessage('Unable to update a todo'); | ||
} finally { | ||
setCompletedTodoIdList([]); | ||
} | ||
}, [todos]); | ||
|
||
const handleRemoveButtonClick = useCallback(async (todoId: number) => { | ||
setCompletedTodoIdList([todoId]); | ||
|
||
try { | ||
await deleteTodo(todoId); | ||
|
||
setTodos(todos.filter(todo => todo.id !== todoId)); | ||
} catch { | ||
showErrorMessage('Unable to delete a todo'); | ||
} finally { | ||
setCompletedTodoIdList([]); | ||
} | ||
}, [todos]); | ||
|
||
const handleFilterBy = useCallback((str: TodoStatus) => { | ||
setFilterBy(str); | ||
}, []); | ||
|
||
const clearCompletedTodos = useCallback(async () => { | ||
const completedTodoIds = todos.filter(todo => todo.completed) | ||
.map(todo => todo.id); | ||
|
||
setCompletedTodoIdList(completedTodoIds); | ||
try { | ||
await Promise.all(completedTodoIds.map(todoId => deleteTodo(todoId))); | ||
|
||
setTodos(todos.filter(todo => !completedTodoIds.includes(todo.id))); | ||
} catch { | ||
showErrorMessage('Unable to delete the todos'); | ||
} finally { | ||
setCompletedTodoIdList([]); | ||
} | ||
}, [todos]); | ||
|
||
useEffect(() => { | ||
const timeoutId = setTimeout(() => { | ||
setHasError(false); | ||
}, 3000); | ||
|
||
return () => { | ||
clearTimeout(timeoutId); | ||
}; | ||
}, [showErrorMessage]); | ||
|
||
useEffect(() => { | ||
getTodos(USER_ID) | ||
.then(todoList => setTodos(todoList)) | ||
.catch(() => showErrorMessage('Unable to load todos')); | ||
}, [USER_ID]); | ||
|
||
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"> | ||
<TodoHeader | ||
isToggleAllButtonVisible={!!todos.length} | ||
isTempTodoTrue={!!tempTodo} | ||
showErrorMessage={showErrorMessage} | ||
onEnterKeyPress={handleEnterKeyPress} | ||
onToggleAllButtonClick={toggleAllTodos} | ||
areAllTodosCompleted={areAllTodosCompleted} | ||
/> | ||
|
||
<TodoListContext.Provider value={{ | ||
visibleTodos, | ||
tempTodo, | ||
completedTodoIdList, | ||
handleTodoRename, | ||
handleToggleButtonClick, | ||
handleRemoveButtonClick, | ||
}} | ||
> | ||
<TodoList /> | ||
</TodoListContext.Provider> | ||
|
||
{todos.length > 0 && ( | ||
<TodoFooter | ||
filter={filterBy} | ||
itemsLeft={activeTodosCount} | ||
onFilter={handleFilterBy} | ||
onClearCompleted={clearCompletedTodos} | ||
completedCount={todos.length - activeTodosCount} | ||
/> | ||
)} | ||
</div> | ||
|
||
<TodoNotification | ||
hasError={hasError} | ||
errorMessage={errorMessage} | ||
onCloseButton={handleCloseButton} | ||
/> | ||
</div> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { NewTodo, Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const getTodos = (userId: number) => { | ||
return client.get<Todo[]>(`/todos?userId=${userId}`); | ||
}; | ||
|
||
export const createTodo = (todo: NewTodo) => { | ||
return client.post<Todo>('/todos', todo); | ||
}; | ||
|
||
export const updateTodo = (todoId: number, todo: NewTodo) => { | ||
return client.patch<Todo>(`/todos/${todoId}`, todo); | ||
}; | ||
|
||
export const deleteTodo = (todoId: number) => { | ||
return client.delete(`/todos/${todoId}`); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import React, { useCallback } from 'react'; | ||
import classNames from 'classnames'; | ||
import { TodoStatus } from '../../types/TodoStatus'; | ||
|
||
type Props = { | ||
onFilter: (str: TodoStatus) => void, | ||
filter: TodoStatus, | ||
itemsLeft: number, | ||
completedCount: number, | ||
onClearCompleted: () => void, | ||
}; | ||
|
||
export const TodoFooter: React.FC<Props> = React.memo(({ | ||
filter, | ||
itemsLeft, | ||
onFilter, | ||
onClearCompleted, | ||
completedCount, | ||
}) => { | ||
const handleClick = useCallback( | ||
(event: React.MouseEvent<HTMLAnchorElement>) => { | ||
const { textContent } = event.currentTarget; | ||
|
||
onFilter(textContent as TodoStatus); | ||
}, [onFilter], | ||
); | ||
|
||
return ( | ||
<footer className="todoapp__footer"> | ||
<span className="todo-count"> | ||
{`${itemsLeft} items left`} | ||
</span> | ||
|
||
<nav className="filter"> | ||
<a | ||
href="#/" | ||
className={classNames('filter__link', { | ||
selected: TodoStatus.All === filter, | ||
})} | ||
onClick={handleClick} | ||
> | ||
All | ||
</a> | ||
|
||
<a | ||
href="#/active" | ||
className={classNames('filter__link', { | ||
selected: TodoStatus.Active === filter, | ||
})} | ||
onClick={handleClick} | ||
> | ||
Active | ||
</a> | ||
|
||
<a | ||
href="#/completed" | ||
className={classNames('filter__link', { | ||
selected: TodoStatus.Completed === filter, | ||
})} | ||
onClick={handleClick} | ||
> | ||
Completed | ||
</a> | ||
</nav> | ||
|
||
<button | ||
type="button" | ||
className="todoapp__clear-completed" | ||
disabled={!completedCount} | ||
onClick={onClearCompleted} | ||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
); | ||
}); |
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.