-
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 #1558
base: master
Are you sure you want to change the base?
solution #1558
Changes from all commits
ea68bc6
d9ce1d6
ed23336
aa3f26f
98245cc
015c0e7
41358e7
2c9669c
c9df513
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,174 @@ | ||
/* 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, useMemo, useState } from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
import * as clientTodo from './api/todos'; | ||
import { getFilteredTodos } from './utils/getFilteredTodos'; | ||
|
||
const USER_ID = 0; | ||
import { ErrorMessage } from './types/ErrorMessage'; | ||
import { Todo } from './types/Todo'; | ||
import { Status } from './types/Status'; | ||
|
||
import { TodoHeader } from './components/TodoHeader'; | ||
import { TodoFooter } from './components/TodoFooter'; | ||
import { ErrorNotification } from './components/ErrorNotification'; | ||
import { TodoList } from './components/TodoList'; | ||
|
||
export const App: React.FC = () => { | ||
if (!USER_ID) { | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [activeStatus, setActiveStatus] = useState(Status.All); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]); | ||
const [errorMessage, setErrorMessage] = useState<ErrorMessage>( | ||
ErrorMessage.Default, | ||
); | ||
|
||
const filteredTodos = useMemo( | ||
() => getFilteredTodos(todos, activeStatus), | ||
[todos, activeStatus], | ||
); | ||
const notCompletedTodos = useMemo( | ||
() => todos.filter(todo => !todo.completed), | ||
[todos], | ||
); | ||
const completedTodos = useMemo( | ||
() => todos.filter(todo => todo.completed), | ||
[todos], | ||
); | ||
const isToogleAll = completedTodos.length === todos.length; | ||
|
||
const onAddTodo = (title: string) => { | ||
setTempTodo({ | ||
id: 0, | ||
title, | ||
userId: clientTodo.USER_ID, | ||
completed: false, | ||
}); | ||
|
||
const newTodo: Omit<Todo, 'id'> = { | ||
title, | ||
userId: clientTodo.USER_ID, | ||
completed: false, | ||
}; | ||
|
||
return clientTodo | ||
.createTodos(newTodo) | ||
.then(todo => setTodos(currentTodos => [...currentTodos, todo])) | ||
.catch(err => { | ||
setErrorMessage(ErrorMessage.UnableToAdd); | ||
throw err; | ||
}) | ||
.finally(() => setTempTodo(null)); | ||
}; | ||
|
||
const onUpdateTodo = (todoToUpdate: Todo) => { | ||
setLoadingTodoIds(prevTodos => [...prevTodos, todoToUpdate.id]); | ||
|
||
return clientTodo | ||
.updateTodo(todoToUpdate) | ||
.then(updatedTodo => { | ||
setTodos(currentTodos => { | ||
return currentTodos.map(todo => | ||
todo.id === updatedTodo.id ? updatedTodo : todo, | ||
); | ||
}); | ||
}) | ||
.catch(err => { | ||
setErrorMessage(ErrorMessage.UnableToUpdate); | ||
throw err; | ||
}) | ||
.finally(() => { | ||
setLoadingTodoIds(prevTodos => | ||
prevTodos.filter(id => todoToUpdate.id !== id), | ||
); | ||
}); | ||
}; | ||
|
||
const onDeleteTodo = (todoId: number) => { | ||
setLoadingTodoIds(prevTodos => [...prevTodos, todoId]); | ||
|
||
clientTodo | ||
.deleteTodo(todoId) | ||
.then(() => | ||
setTodos(currentTodos => | ||
currentTodos.filter(todo => todo.id !== todoId), | ||
), | ||
) | ||
.catch(() => { | ||
setErrorMessage(ErrorMessage.UnableToDelete); | ||
}) | ||
.finally(() => | ||
setLoadingTodoIds(prevTodos => prevTodos.filter(id => todoId !== id)), | ||
); | ||
}; | ||
|
||
const onDeleteAllCompleted = () => { | ||
completedTodos.forEach(todo => onDeleteTodo(todo.id)); | ||
}; | ||
|
||
const onToggleAll = () => { | ||
if (todos.every(todo => todo.completed)) { | ||
todos.forEach(todo => onUpdateTodo({ ...todo, completed: false })); | ||
} else { | ||
todos.filter(todo => { | ||
if (!todo.completed) { | ||
onUpdateTodo({ ...todo, completed: true }); | ||
} | ||
}); | ||
} | ||
}; | ||
|
||
useEffect(() => { | ||
clientTodo | ||
.getTodos() | ||
.then(data => setTodos(data)) | ||
.catch(() => { | ||
setErrorMessage(ErrorMessage.UnableToLoad); | ||
}); | ||
}, []); | ||
|
||
if (!clientTodo.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 | ||
error={errorMessage} | ||
isToogleAll={todos.length === 0 ? null : isToogleAll} | ||
isInputDisablet={!!tempTodo} | ||
isDeletedTodos={todos.length} | ||
onAddTodo={onAddTodo} | ||
onToggleAll={onToggleAll} | ||
setErrorMessage={setErrorMessage} | ||
/> | ||
|
||
<TodoList | ||
tempTodo={tempTodo} | ||
filteredTodos={filteredTodos} | ||
loadingTodoIds={loadingTodoIds} | ||
onDeleteTodo={onDeleteTodo} | ||
onUpdateTodo={onUpdateTodo} | ||
/> | ||
|
||
{!!todos.length && ( | ||
<TodoFooter | ||
activeStatus={activeStatus} | ||
completedTodos={completedTodos.length} | ||
notCompletedTodos={notCompletedTodos.length} | ||
onDeleteAllCompleted={onDeleteAllCompleted} | ||
setActiveStatus={setActiveStatus} | ||
/> | ||
)} | ||
</div> | ||
|
||
<ErrorNotification | ||
error={errorMessage} | ||
setErrorMessage={setErrorMessage} | ||
/> | ||
</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 = 2135; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const createTodos = ({ title, userId, completed }: Omit<Todo, 'id'>) => { | ||
return client.post<Todo>(`/todos`, { title, userId, completed }); | ||
}; | ||
|
||
export const deleteTodo = (id: number) => { | ||
return client.delete(`/todos/${id}`); | ||
}; | ||
|
||
export const updateTodo = ({ id, title, completed, userId }: Todo) => { | ||
return client.patch<Todo>(`/todos/${id}`, { title, completed, userId }); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import React, { useEffect } from 'react'; | ||
import cn from 'classnames'; | ||
import { ErrorMessage } from '../types/ErrorMessage'; | ||
|
||
type Props = { | ||
error: string; | ||
setErrorMessage: (error: ErrorMessage) => void; | ||
}; | ||
|
||
export const ErrorNotification: React.FC<Props> = props => { | ||
const { error, setErrorMessage } = props; | ||
|
||
useEffect(() => { | ||
if (error === ErrorMessage.Default) { | ||
return; | ||
} | ||
|
||
const timer = setTimeout(() => { | ||
setErrorMessage(ErrorMessage.Default); | ||
}, 3000); | ||
|
||
return () => clearTimeout(timer); | ||
}, [error, setErrorMessage]); | ||
|
||
return ( | ||
<div | ||
data-cy="ErrorNotification" | ||
className={cn( | ||
'notification', | ||
'is-danger', | ||
'is-light has-text-weight-normal', | ||
{ hidden: !error }, | ||
)} | ||
> | ||
<button | ||
data-cy="HideErrorButton" | ||
type="button" | ||
className="delete" | ||
onClick={() => setErrorMessage} | ||
/> | ||
{error} | ||
</div> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,56 @@ | ||||||
/* eslint-disable prettier/prettier */ | ||||||
import React from 'react'; | ||||||
import cn from 'classnames'; | ||||||
import { Status } from '../types/Status'; | ||||||
|
||||||
type Props = { | ||||||
activeStatus: Status; | ||||||
completedTodos: number; | ||||||
notCompletedTodos: number; | ||||||
onDeleteAllCompleted: () => void; | ||||||
setActiveStatus: (status: Status) => void; | ||||||
}; | ||||||
|
||||||
export const TodoFooter: React.FC<Props> = props => { | ||||||
const { | ||||||
activeStatus, | ||||||
completedTodos, | ||||||
notCompletedTodos, | ||||||
onDeleteAllCompleted, | ||||||
setActiveStatus, | ||||||
} = props; | ||||||
|
||||||
return ( | ||||||
<footer className="todoapp__footer" data-cy="Footer"> | ||||||
<span className="todo-count" data-cy="TodosCounter"> | ||||||
{notCompletedTodos} items left | ||||||
</span> | ||||||
|
||||||
<nav className="filter" data-cy="Filter"> | ||||||
{Object.values(Status).map(status => ( | ||||||
<a | ||||||
key={status} | ||||||
data-cy={`FilterLink${status}`} | ||||||
href={status === 'All' ? '#/' : `#/${status.toLowerCase()}`} | ||||||
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
let's use enum |
||||||
className={cn('filter__link', { | ||||||
selected: activeStatus === status, | ||||||
})} | ||||||
onClick={() => setActiveStatus(status)} | ||||||
> | ||||||
{status} | ||||||
</a> | ||||||
))} | ||||||
</nav> | ||||||
|
||||||
<button | ||||||
type="button" | ||||||
className="todoapp__clear-completed" | ||||||
data-cy="ClearCompletedButton" | ||||||
disabled={completedTodos === 0} | ||||||
onClick={onDeleteAllCompleted} | ||||||
> | ||||||
Clear completed | ||||||
</button> | ||||||
</footer> | ||||||
); | ||||||
}; |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,76 @@ | ||||||
import React, { useEffect, useRef, useState } from 'react'; | ||||||
import cn from 'classnames'; | ||||||
import { ErrorMessage } from '../types/ErrorMessage'; | ||||||
|
||||||
type Props = { | ||||||
error: ErrorMessage; | ||||||
isToogleAll: boolean | 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. In what case should it be null? it's a bit confusing 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. in this case boolean defines |
||||||
isInputDisablet: boolean; | ||||||
isDeletedTodos: number; | ||||||
onAddTodo: (title: string) => Promise<void>; | ||||||
onToggleAll: () => void; | ||||||
setErrorMessage: (error: ErrorMessage) => void; | ||||||
}; | ||||||
|
||||||
export const TodoHeader: React.FC<Props> = props => { | ||||||
const { | ||||||
error, | ||||||
isToogleAll, | ||||||
isInputDisablet, | ||||||
isDeletedTodos, | ||||||
onAddTodo, | ||||||
onToggleAll, | ||||||
setErrorMessage, | ||||||
} = props; | ||||||
|
||||||
const [title, setTitle] = useState(''); | ||||||
const inputRef = useRef<HTMLInputElement | null>(null); | ||||||
|
||||||
useEffect(() => { | ||||||
if (inputRef.current) { | ||||||
inputRef.current.focus(); | ||||||
} | ||||||
}, [inputRef, isInputDisablet, isDeletedTodos]); | ||||||
|
||||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { | ||||||
event.preventDefault(); | ||||||
|
||||||
if (error !== ErrorMessage.Default) { | ||||||
setErrorMessage(ErrorMessage.Default); | ||||||
} | ||||||
|
||||||
if (!title.trim()) { | ||||||
setErrorMessage(ErrorMessage.EmptyTitle); | ||||||
|
||||||
return; | ||||||
} | ||||||
|
||||||
onAddTodo(title.trim()).then(() => setTitle('')); | ||||||
}; | ||||||
|
||||||
return ( | ||||||
<header className="todoapp__header"> | ||||||
{isToogleAll !== 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.
Suggested change
|
||||||
<button | ||||||
type="button" | ||||||
className={cn('todoapp__toggle-all', { active: isToogleAll })} | ||||||
data-cy="ToggleAllButton" | ||||||
onClick={onToggleAll} | ||||||
/> | ||||||
)} | ||||||
|
||||||
<form onSubmit={handleSubmit}> | ||||||
<input | ||||||
data-cy="NewTodoField" | ||||||
type="text" | ||||||
className="todoapp__new-todo" | ||||||
placeholder="What needs to be done?" | ||||||
ref={inputRef} | ||||||
value={title} | ||||||
onChange={event => setTitle(event.target.value)} | ||||||
disabled={isInputDisablet} | ||||||
/> | ||||||
</form> | ||||||
</header> | ||||||
); | ||||||
}; |
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.
let's move
/todos
into const and reuse