-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Solution 3/3 #2207
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
base: master
Are you sure you want to change the base?
Solution 3/3 #2207
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,297 @@ | ||
| /* eslint-disable max-len */ | ||
| /* eslint-disable jsx-a11y/label-has-associated-control */ | ||
| /* eslint-disable jsx-a11y/control-has-associated-label */ | ||
| import React from 'react'; | ||
| import React, { useEffect, useRef, useState } from 'react'; | ||
| import { UserWarning } from './UserWarning'; | ||
| import * as todoService from './api/todos'; | ||
| import { Todo } from './types/Todo'; | ||
| import classNames from 'classnames'; | ||
| import { TodoList } from './components/TodoList'; | ||
| import { TodoItem } from './components/TodoItem'; | ||
| import { NewTodo } from './types/NewTodo'; | ||
|
|
||
| const USER_ID = 0; | ||
| const ERROR_MESSAGES = { | ||
| load: 'Unable to load todos', | ||
| title: 'Title should not be empty', | ||
| add: 'Unable to add a todo', | ||
| delete: 'Unable to delete a todo', | ||
| update: 'Unable to update a todo', | ||
| }; | ||
|
|
||
| export const App: React.FC = () => { | ||
| if (!USER_ID) { | ||
| const [todos, setTodos] = useState<Todo[]>([]); | ||
| const [title, setTitle] = useState(''); | ||
| const [status, setStatus] = useState(''); | ||
| const [errorMessage, setErrorMessage] = useState<string | null>(null); | ||
| const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
| const [loadingIds, setLoadingIds] = useState<number[]>([]); | ||
|
|
||
| const normalizedTitle = title.trim(); | ||
| const isAllCompleted = todos.every(todo => todo.completed); | ||
| const hasCompleted = todos.some(todo => todo.completed); | ||
| const filteringByStatus = todos.filter(todo => { | ||
| if (status === 'active') { | ||
| return !todo.completed; | ||
| } | ||
|
|
||
| if (status === 'completed') { | ||
| return todo.completed; | ||
| } | ||
|
|
||
| return true; | ||
| }); | ||
| const newTodo = (todoTitle: string): NewTodo => { | ||
| return { | ||
| userId: todoService.USER_ID, | ||
| title: todoTitle, | ||
| completed: false, | ||
| }; | ||
| }; | ||
|
|
||
| /* get todos */ | ||
| useEffect(() => { | ||
| todoService | ||
| .getTodos() | ||
| .then(setTodos) | ||
| .catch(() => setErrorMessage(ERROR_MESSAGES.load)); | ||
| }, []); | ||
|
|
||
| /* errors */ | ||
| useEffect(() => { | ||
| if (!errorMessage) { | ||
| return; | ||
| } | ||
|
|
||
| const timer = setTimeout(() => setErrorMessage(null), 3000); | ||
|
|
||
| return () => clearTimeout(timer); | ||
| }, [errorMessage]); | ||
|
|
||
| /* input focus */ | ||
| const inputRef = useRef<HTMLInputElement>(null); | ||
|
|
||
| useEffect(() => { | ||
| inputRef.current?.focus(); | ||
| }, [tempTodo]); | ||
|
|
||
| /* deleting */ | ||
| function deleteTodo(todoId: number) { | ||
| setLoadingIds(prev => [...prev, todoId]); | ||
| todoService | ||
| .deleteTodo(todoId) | ||
| .then(() => setTodos(prev => prev.filter(todo => todo.id !== todoId))) | ||
| .catch(() => { | ||
| setErrorMessage(ERROR_MESSAGES.delete); | ||
| setTempTodo(null); | ||
| }) | ||
| .finally(() => { | ||
| setLoadingIds(loadingIds.filter(id => id !== todoId)); | ||
| inputRef?.current?.focus(); | ||
| }); | ||
| } | ||
|
|
||
| const clearCompleted = () => { | ||
| todos.filter(todo => todo.completed).forEach(todo => deleteTodo(todo.id)); | ||
| }; | ||
|
|
||
| /* toggle */ | ||
| const onToggle = (todo: Todo) => { | ||
| setLoadingIds(prev => [...prev, todo.id]); | ||
| const toggled = { ...todo, completed: !todo.completed }; | ||
|
|
||
| todoService | ||
| .updateTodo(toggled) | ||
| .then(toggledTodo => { | ||
| setTodos(prev => | ||
| prev.map(t => (t.id === toggledTodo.id ? toggledTodo : t)), | ||
| ); | ||
| }) | ||
| .catch(() => setErrorMessage(ERROR_MESSAGES.update)) | ||
| .finally(() => setLoadingIds(prev => prev.filter(id => id !== todo.id))); | ||
| }; | ||
|
|
||
| const toggleAll = () => { | ||
| if (hasCompleted && !isAllCompleted) { | ||
| return todos.filter(todo => !todo.completed).forEach(t => onToggle(t)); | ||
| } | ||
|
|
||
| return todos.forEach(todo => onToggle(todo)); | ||
| }; | ||
|
|
||
| const onUpdate = (updatedTodo: Todo) => { | ||
| setLoadingIds(prev => [...prev, updatedTodo.id]); | ||
|
|
||
| return todoService | ||
| .updateTodo(updatedTodo) | ||
| .then(() => | ||
| setTodos(prev => | ||
| prev.map(t => (t.id === updatedTodo.id ? updatedTodo : t)), | ||
| ), | ||
| ) | ||
| .catch(() => { | ||
| setErrorMessage(ERROR_MESSAGES.update); | ||
| throw new Error(); | ||
| }) | ||
| .finally(() => | ||
| setLoadingIds(prev => prev.filter(id => id !== updatedTodo.id)), | ||
| ); | ||
| }; | ||
|
|
||
| if (!todoService.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"> | ||
| {/* this button should have `active` class only if all todos are completed */} | ||
| {todos.length > 0 && ( | ||
| <button | ||
| type="button" | ||
| className={classNames('todoapp__toggle-all', { | ||
| active: isAllCompleted, | ||
| })} | ||
| data-cy="ToggleAllButton" | ||
| onClick={toggleAll} | ||
| /> | ||
| )} | ||
|
|
||
| {/* Add a todo on form submit */} | ||
| <form | ||
| onSubmit={e => { | ||
| e.preventDefault(); | ||
|
|
||
| if (!normalizedTitle) { | ||
| setErrorMessage(ERROR_MESSAGES.title); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| setTempTodo({ | ||
| ...newTodo(normalizedTitle), | ||
| id: 0, | ||
| }); | ||
| todoService | ||
| .addTodo(newTodo(normalizedTitle)) | ||
| .then(addedTodo => { | ||
| setTodos([...todos, addedTodo]); | ||
| setTitle(''); | ||
| setTempTodo(null); | ||
| }) | ||
| .catch(() => { | ||
| setErrorMessage(ERROR_MESSAGES.add); | ||
| setTempTodo(null); | ||
| }); | ||
| }} | ||
|
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 to separate fn |
||
| > | ||
| <input | ||
| data-cy="NewTodoField" | ||
| type="text" | ||
| className="todoapp__new-todo" | ||
| placeholder="What needs to be done?" | ||
| value={title} | ||
| onChange={e => setTitle(e.target.value)} | ||
| ref={inputRef} | ||
| disabled={tempTodo !== null} | ||
| /> | ||
| </form> | ||
| </header> | ||
|
|
||
| <TodoList | ||
| todos={filteringByStatus} | ||
| onDelete={deleteTodo} | ||
| loadingIds={loadingIds} | ||
| onChecked={onToggle} | ||
| onChange={onUpdate} | ||
| /> | ||
|
|
||
| {tempTodo && ( | ||
| <TodoItem | ||
| todo={tempTodo} | ||
| isLoading={true} | ||
| deleteItem={() => {}} | ||
| isComplete={() => {}} | ||
| isChange={() => Promise.resolve()} | ||
| /> | ||
| )} | ||
|
|
||
| {/* Hide the footer if there are no todos */} | ||
| {todos.length > 0 && ( | ||
| <footer className="todoapp__footer" data-cy="Footer"> | ||
| <span className="todo-count" data-cy="TodosCounter"> | ||
| {todos.filter(todo => !todo.completed).length} items left | ||
| </span> | ||
|
|
||
| {/* Active link should have the 'selected' class */} | ||
| <nav className="filter" data-cy="Filter"> | ||
|
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. create separate |
||
| <a | ||
| href="#/" | ||
| className={classNames('filter__link', { | ||
| selected: status === '', | ||
| })} | ||
| data-cy="FilterLinkAll" | ||
| onClick={() => setStatus('')} | ||
| > | ||
| All | ||
| </a> | ||
|
|
||
| <a | ||
| href="#/active" | ||
| className={classNames('filter__link', { | ||
| selected: status === 'active', | ||
| })} | ||
| data-cy="FilterLinkActive" | ||
| onClick={() => setStatus('active')} | ||
| > | ||
| Active | ||
| </a> | ||
|
|
||
| <a | ||
| href="#/completed" | ||
| className={classNames('filter__link', { | ||
| selected: status === 'completed', | ||
| })} | ||
| data-cy="FilterLinkCompleted" | ||
| onClick={() => setStatus('completed')} | ||
| > | ||
| Completed | ||
| </a> | ||
|
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. you may add all your filter values to |
||
| </nav> | ||
|
|
||
| {/* this button should be disabled if there are no completed todos */} | ||
| <button | ||
| type="button" | ||
| className="todoapp__clear-completed" | ||
| data-cy="ClearCompletedButton" | ||
| onClick={clearCompleted} | ||
| disabled={!hasCompleted} | ||
| > | ||
| Clear completed | ||
| </button> | ||
| </footer> | ||
| )} | ||
| </div> | ||
|
|
||
| <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={() => setErrorMessage(null)} | ||
| /> | ||
| {/* show only one message at a time */} | ||
| {errorMessage} | ||
| </div> | ||
| </div> | ||
| ); | ||
| }; | ||
| 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 USER_ID = 4201; | ||
|
|
||
| export const getTodos = () => { | ||
| return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
| }; | ||
|
|
||
| export const addTodo = (todo: Omit<Todo, 'id'>) => { | ||
| return client.post<Todo>('/todos', todo); | ||
| }; | ||
|
|
||
| export const updateTodo = (todo: Todo) => { | ||
| return client.patch<Todo>(`/todos/${todo.id}`, todo); | ||
| }; | ||
|
|
||
| export const deleteTodo = (todoId: number) => { | ||
| return client.delete(`/todos/${todoId}`); | ||
| }; |
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.
you may move this to
/typesand useenuminstead