-
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
Develop #789
Develop #789
Changes from 3 commits
1091178
ddb1cc6
4b7d941
c6ed7e7
4f8d5fd
affb0aa
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,25 @@ | ||
/* eslint-disable max-len */ | ||
/* eslint-disable jsx-a11y/control-has-associated-label */ | ||
import React from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
|
||
const USER_ID = 0; | ||
import { TodoApp } from './components/TodoApp/TodoApp'; | ||
import { | ||
TodosContextProvider, | ||
} from './components/TodosContextProvider/TodosContextProvider'; | ||
import { USER_ID } from './utils/UserId'; | ||
import { | ||
ErrorContextProvider, | ||
} from './components/ErrorContextProvider/ErrorContextProvider'; | ||
|
||
export const App: React.FC = () => { | ||
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> | ||
<TodosContextProvider> | ||
<ErrorContextProvider> | ||
<TodoApp /> | ||
</ErrorContextProvider> | ||
</TodosContextProvider> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
|
||
export const getTodos = (userId: number) => { | ||
return client.get<Todo[]>(`/todos?userId=${userId}`); | ||
}; | ||
|
||
export const postTodo = (data: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>('/todos', data); | ||
}; | ||
|
||
export const deleteTodo = (todoId: number) => { | ||
return client.delete(`/todos/${todoId}`); | ||
}; | ||
|
||
export const updateTodo = (todoId: number, changes: object) => { | ||
return client.patch(`/todos/${todoId}`, changes); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import React, { useState } from 'react'; | ||
|
||
export const ErrorContext = React.createContext({ | ||
errorMessage: '', | ||
setErrorMessage: () => {}, | ||
hasError: false, | ||
setHasError: () => {}, | ||
onNewError: () => {}, | ||
} as ErrorContextProps); | ||
|
||
type ErrorContextProps = { | ||
errorMessage: string, | ||
setErrorMessage: React.Dispatch<React.SetStateAction<string>>, | ||
hasError: boolean, | ||
setHasError: React.Dispatch<React.SetStateAction<boolean>>, | ||
onNewError: (error: string) => void, | ||
}; | ||
|
||
type Props = { | ||
children: React.ReactNode, | ||
}; | ||
|
||
export const ErrorContextProvider: React.FC<Props> = ({ children }) => { | ||
const [errorMessage, setErrorMessage] = useState(''); | ||
const [hasError, setHasError] = useState(false); | ||
|
||
const onNewError = (error: string) => { | ||
setErrorMessage(error); | ||
setHasError(true); | ||
|
||
setTimeout(() => { | ||
setHasError(false); | ||
}, 3000); | ||
}; | ||
|
||
const initialValue = { | ||
errorMessage, | ||
setErrorMessage, | ||
hasError, | ||
setHasError, | ||
onNewError, | ||
}; | ||
|
||
return ( | ||
<ErrorContext.Provider value={initialValue}> | ||
{children} | ||
</ErrorContext.Provider> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import React from 'react'; | ||
import classNames from 'classnames'; | ||
import { FilterKey } from '../../types/FilterKey'; | ||
|
||
type Props = { | ||
filterKey: FilterKey, | ||
onClick: (key: FilterKey) => void | ||
}; | ||
|
||
export const Filter: React.FC<Props> = ({ filterKey, onClick }) => { | ||
return ( | ||
<nav className="filter" data-cy="Filter"> | ||
<a | ||
data-cy="FilterLinkAll" | ||
href="#/" | ||
className={classNames('filter__link', { | ||
selected: filterKey === FilterKey.All, | ||
})} | ||
onClick={() => onClick(FilterKey.All)} | ||
> | ||
All | ||
</a> | ||
|
||
<a | ||
data-cy="FilterLinkActive" | ||
href="#/active" | ||
className={classNames('filter__link', { | ||
selected: filterKey === FilterKey.Active, | ||
})} | ||
onClick={() => onClick(FilterKey.Active)} | ||
> | ||
Active | ||
</a> | ||
|
||
<a | ||
data-cy="FilterLinkCompleted" | ||
href="#/completed" | ||
className={classNames('filter__link', { | ||
selected: filterKey === FilterKey.Completed, | ||
})} | ||
onClick={() => onClick(FilterKey.Completed)} | ||
> | ||
Completed | ||
</a> | ||
</nav> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,75 @@ | ||||||
import React, { | ||||||
useContext, | ||||||
useEffect, | ||||||
useRef, | ||||||
useState, | ||||||
} from 'react'; | ||||||
import { Todo } from '../../types/Todo'; | ||||||
import { postTodo } from '../../api/todos'; | ||||||
import { TodosContext } from '../TodosContextProvider/TodosContextProvider'; | ||||||
import { USER_ID } from '../../utils/UserId'; | ||||||
import { ErrorContext } from '../ErrorContextProvider/ErrorContextProvider'; | ||||||
|
||||||
type Props = { | ||||||
setTempTodo: (todo: Todo | null) => void, | ||||||
tempTodo: Todo | null, | ||||||
}; | ||||||
|
||||||
export const NewTodo: React.FC<Props> = ({ | ||||||
setTempTodo, tempTodo, | ||||||
}) => { | ||||||
const { onNewError } = useContext(ErrorContext); | ||||||
const { setTodos, todos } = useContext(TodosContext); | ||||||
const [newTodoTitle, setNewTodoTitle] = useState(''); | ||||||
const titleInput = useRef<HTMLInputElement | null>(null); | ||||||
|
||||||
useEffect(() => { | ||||||
if (titleInput.current) { | ||||||
titleInput.current.focus(); | ||||||
} | ||||||
}, [todos, tempTodo]); | ||||||
|
||||||
const handleAddingTodo = (event: React.FormEvent<HTMLFormElement>) => { | ||||||
event.preventDefault(); | ||||||
|
||||||
if (!newTodoTitle.trim()) { | ||||||
onNewError('Title should not be empty'); | ||||||
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 would be good to put error texts in a separate constant. |
||||||
|
||||||
return; | ||||||
} | ||||||
|
||||||
const newTodo: Omit<Todo, 'id'> = { | ||||||
userId: USER_ID, | ||||||
title: newTodoTitle.trim(), | ||||||
completed: false, | ||||||
}; | ||||||
|
||||||
postTodo(newTodo) | ||||||
.then((response) => { | ||||||
setNewTodoTitle(''); | ||||||
setTodos((prevTodos) => [...prevTodos, response]); | ||||||
}) | ||||||
.catch(() => onNewError('Unable to add a todo')) | ||||||
.finally(() => setTempTodo(null)); | ||||||
|
||||||
setTempTodo({ | ||||||
...newTodo, | ||||||
id: 0, | ||||||
}); | ||||||
}; | ||||||
|
||||||
return ( | ||||||
<form onSubmit={handleAddingTodo}> | ||||||
<input | ||||||
data-cy="NewTodoField" | ||||||
ref={titleInput} | ||||||
type="text" | ||||||
className="todoapp__new-todo" | ||||||
placeholder="What needs to be done?" | ||||||
value={newTodoTitle} | ||||||
onChange={(event) => setNewTodoTitle(event.target.value)} | ||||||
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
|
||||||
disabled={!!tempTodo} | ||||||
/> | ||||||
</form> | ||||||
); | ||||||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
import { | ||
useContext, | ||
useEffect, | ||
useMemo, | ||
useState, | ||
} from 'react'; | ||
import classNames from 'classnames'; | ||
import { Filter } from '../Filter/Filter'; | ||
import { NewTodo } from '../NewTodo/NewTodo'; | ||
import { TodoList } from '../TodoList/TodoList'; | ||
import { | ||
TodosContext, | ||
} from '../TodosContextProvider/TodosContextProvider'; | ||
import { TodoError } from '../TodoError/TodoError'; | ||
import { deleteTodo, getTodos, updateTodo } from '../../api/todos'; | ||
import { FilterKey } from '../../types/FilterKey'; | ||
import { Todo } from '../../types/Todo'; | ||
import { USER_ID } from '../../utils/UserId'; | ||
import { ErrorContext } from '../ErrorContextProvider/ErrorContextProvider'; | ||
|
||
function getFilteredTodos(key: FilterKey, todos: Todo[]) { | ||
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. I would move this to separate file as a helper function |
||
switch (key) { | ||
case FilterKey.All: | ||
return todos; | ||
case FilterKey.Active: | ||
return todos.filter(({ completed }) => !completed); | ||
case FilterKey.Completed: | ||
return todos.filter(({ completed }) => completed); | ||
default: | ||
return todos; | ||
} | ||
} | ||
|
||
export const TodoApp = () => { | ||
const { onNewError } = useContext(ErrorContext); | ||
const { todos, setTodos, setTodoIdsWithLoader } = useContext(TodosContext); | ||
const [filterKey, setFilterKey] = useState<FilterKey>(FilterKey.All); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
|
||
const areAllTodosCompleted = todos.every(({ completed }) => completed); | ||
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. I know that "are" would be lexically correct, but in programming it is customary to use "is" in all cases :) |
||
const visibleTodos = useMemo( | ||
() => getFilteredTodos(filterKey, todos), | ||
[todos, filterKey], | ||
); | ||
const activeTodos = todos.filter(({ completed }) => !completed); | ||
const hasCompletedTodo = todos.some(({ completed }) => completed); | ||
|
||
useEffect(() => { | ||
getTodos(USER_ID) | ||
.then(setTodos) | ||
.catch(() => onNewError('Unable to load todos')); | ||
}, []); | ||
|
||
const handleAllTodosToggle = () => { | ||
const todosToUpdate = todos.filter( | ||
({ completed }) => completed === areAllTodosCompleted, | ||
); | ||
|
||
setTodoIdsWithLoader( | ||
prevTodoIds => [...prevTodoIds, ...todosToUpdate.map(({ id }) => id)], | ||
); | ||
|
||
todosToUpdate.forEach(todo => { | ||
updateTodo(todo.id, { completed: !todo.completed }) | ||
.then(() => { | ||
const todosCopy = [...todos]; | ||
const searchedTodo = todos.find( | ||
({ id }) => todo.id === id, | ||
) as Todo; | ||
|
||
searchedTodo.completed = !searchedTodo.completed; | ||
|
||
setTodos(todosCopy); | ||
}) | ||
.catch(() => onNewError('Unable to update a todo')) | ||
.finally(() => setTodoIdsWithLoader( | ||
prevTodoIds => prevTodoIds.filter((todoId) => todoId !== todo.id), | ||
)); | ||
}); | ||
}; | ||
|
||
const handleCompletedTodosDelete = () => { | ||
const completedTodos = todos.filter(({ completed }) => completed); | ||
|
||
setTodoIdsWithLoader(prevTodoIds => { | ||
return [...prevTodoIds, ...completedTodos.map(({ id }) => id)]; | ||
}); | ||
|
||
completedTodos.forEach(todo => { | ||
deleteTodo(todo.id) | ||
.then(() => { | ||
setTodos(prevTodos => prevTodos.filter(({ id }) => id !== todo.id)); | ||
}) | ||
.catch(() => onNewError('Unable to delete a todo')) | ||
.finally(() => setTodoIdsWithLoader( | ||
prevTodoIds => prevTodoIds.filter((id) => todo.id !== id), | ||
)); | ||
}); | ||
}; | ||
|
||
return ( | ||
<div className="todoapp"> | ||
<h1 className="todoapp__title">todos</h1> | ||
<div className="todoapp__content"> | ||
<header className="todoapp__header"> | ||
{!!todos.length && ( | ||
<button | ||
type="button" | ||
data-cy="ToggleAllButton" | ||
className={classNames('todoapp__toggle-all', { | ||
active: areAllTodosCompleted, | ||
})} | ||
aria-label="toggle_all_todos" | ||
onClick={handleAllTodosToggle} | ||
/> | ||
)} | ||
|
||
<NewTodo | ||
setTempTodo={setTempTodo} | ||
tempTodo={tempTodo} | ||
/> | ||
</header> | ||
|
||
<TodoList | ||
todos={visibleTodos} | ||
tempTodo={tempTodo} | ||
/> | ||
|
||
{!!todos.length && ( | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
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. I would move footer to separate component |
||
<span className="todo-count" data-cy="TodosCounter"> | ||
{`${activeTodos.length} items left`} | ||
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. If there is one item, there should not be a plural in the text. 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. |
||
</span> | ||
<Filter | ||
filterKey={filterKey} | ||
onClick={setFilterKey} | ||
/> | ||
<button | ||
type="button" | ||
data-cy="ClearCompletedButton" | ||
className={classNames('todoapp__clear-completed', { | ||
'is-invisible': !hasCompletedTodo, | ||
})} | ||
onClick={handleCompletedTodosDelete} | ||
disabled={!hasCompletedTodo} | ||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
)} | ||
|
||
<TodoError /> | ||
</div> | ||
</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.
changes
have to have another type instead of an object, as we update a todo in this case, and not every object suits.You can use some of the utility types, for example,
Partial
.https://www.typescriptlang.org/docs/handbook/utility-types.html