-
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
task solution_v1 #1530
Open
inesshtepa
wants to merge
7
commits into
mate-academy:master
Choose a base branch
from
inesshtepa:develop
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
task solution_v1 #1530
Changes from 2 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1250ebe
task solution_v1
inesshtepa e2f27bd
task solution_v2
inesshtepa 13b7553
task solution_v2
inesshtepa 97334d4
task solution_v3
inesshtepa 0da38f6
task solutopn_v4
inesshtepa 809c804
update_footer
inesshtepa ce979e7
update_footer
inesshtepa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,293 @@ | ||
/* 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, useRef, useState } from 'react'; | ||
import { UserWarning } from './UserWarning'; | ||
|
||
const USER_ID = 0; | ||
import { USER_ID } from './api/todos'; | ||
import { Todo } from './types/Todo'; | ||
import * as todoService from './api/todos'; | ||
import { FilterOptions } from './types/FilterOptions'; | ||
import { Todolist } from './components/TodoList'; | ||
import { TodoItem } from './components/TodoItem'; | ||
import classNames from 'classnames'; | ||
|
||
export const App: React.FC = () => { | ||
const [loading, setLoading] = useState(false); | ||
const [todos, setTodos] = useState<Todo[]>([]); | ||
const [currentFilter, setCurrentFilter] = useState<FilterOptions>( | ||
FilterOptions.All, | ||
); | ||
const [errorMessage, setErrorMessage] = useState(''); | ||
const [newTodoTitle, setNewTodoTitle] = useState(''); | ||
const [tempTodo, setTempTodo] = useState<Todo | null>(null); | ||
const [deletingId, setDeletingID] = useState([0]); | ||
const [loadingIds, setLoadingIds] = useState<number[]>([]); | ||
|
||
const inputRef = useRef<HTMLInputElement | null>(null); | ||
|
||
const handleDelete = (todoId: number): Promise<void> => { | ||
setDeletingID(prev => [...prev, todoId]); | ||
|
||
return todoService | ||
.deleteTodos(todoId) | ||
.then(() => { | ||
setLoading(true); | ||
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== todoId)); | ||
}) | ||
.catch(() => { | ||
setErrorMessage('Unable to delete a todo'); | ||
}) | ||
.finally(() => { | ||
setLoading(false); | ||
setDeletingID((prev: number[]) => prev.filter(id => id !== todoId)); | ||
setTimeout(() => setErrorMessage(''), 3000); | ||
}); | ||
}; | ||
|
||
const handleUpdateTodo = (updatedTodo: Todo) => { | ||
setLoadingIds(prevState => [...prevState, updatedTodo.id]); | ||
|
||
return todoService | ||
.updateTodos(updatedTodo) | ||
.then(() => { | ||
setTodos(currentTodos => | ||
currentTodos.map(item => | ||
item.id === updatedTodo.id ? updatedTodo : item, | ||
), | ||
); | ||
}) | ||
.catch(error => { | ||
setErrorMessage('Unable to update a todo'); | ||
throw error; | ||
}) | ||
.finally(() => { | ||
setLoadingIds(prevState => | ||
prevState.filter(id => id !== updatedTodo.id), | ||
); | ||
setTimeout(() => setErrorMessage(''), 3000); | ||
}); | ||
}; | ||
|
||
const filteredTodos = useMemo(() => { | ||
switch (currentFilter) { | ||
case FilterOptions.Active: | ||
return todos.filter(todo => !todo.completed); | ||
case FilterOptions.Completed: | ||
return todos.filter(todo => todo.completed); | ||
default: | ||
return todos; | ||
} | ||
}, [currentFilter, todos]); | ||
|
||
const newTodo: Todo = { | ||
id: 0, | ||
title: newTodoTitle.trim(), | ||
userId: USER_ID, | ||
completed: false, | ||
}; | ||
|
||
const handleSubmit = async (event: React.FormEvent) => { | ||
event.preventDefault(); | ||
|
||
if (!newTodoTitle.trim()) { | ||
setErrorMessage('Title should not be empty'); | ||
inputRef.current?.focus(); | ||
setTimeout(() => setErrorMessage(''), 3000); | ||
|
||
return; | ||
} | ||
|
||
setTempTodo(newTodo); | ||
|
||
try { | ||
const addNewTodo = await todoService.postTodo(newTodo); | ||
|
||
setTodos(prevTodos => [...prevTodos, addNewTodo]); | ||
setNewTodoTitle(''); | ||
setErrorMessage(''); | ||
} catch { | ||
setErrorMessage('Unable to add a todo'); | ||
} finally { | ||
setTempTodo(null); | ||
inputRef.current?.focus(); | ||
setTimeout(() => setErrorMessage(''), 3000); | ||
} | ||
}; | ||
|
||
const activeTodos = todos.filter(todo => !todo.completed).length; | ||
|
||
const completedAllTodos = () => { | ||
const allCompleted = todos.every(todo => todo.completed); | ||
|
||
if (allCompleted) { | ||
todos.forEach(todo => { | ||
handleUpdateTodo({ | ||
...todo, | ||
completed: false, | ||
}); | ||
}); | ||
} else { | ||
todos | ||
.filter(todo => !todo.completed) | ||
.forEach(todo => { | ||
handleUpdateTodo({ | ||
...todo, | ||
completed: true, | ||
}); | ||
}); | ||
} | ||
}; | ||
|
||
const toggleTodoCompletion = (id: number) => { | ||
setTodos( | ||
todos.map(todo => | ||
todo.id === id ? { ...todo, completed: !todo.completed } : todo, | ||
), | ||
); | ||
}; | ||
|
||
useEffect(() => { | ||
if (inputRef.current) { | ||
inputRef.current.focus(); | ||
} | ||
}, [todos, inputRef]); | ||
|
||
const loadTodos = () => { | ||
setLoading(true); | ||
|
||
todoService | ||
.getTodos() | ||
.then(setTodos) | ||
.catch(() => setErrorMessage('Unable to load todos')) | ||
.finally(() => { | ||
setLoading(false); | ||
inputRef.current?.focus(); | ||
setTimeout(() => setErrorMessage(''), 3000); | ||
}); | ||
}; | ||
|
||
useEffect(loadTodos, []); | ||
|
||
if (!USER_ID) { | ||
return <UserWarning />; | ||
} | ||
|
||
const handleClearCompleted = () => { | ||
const completedTodoId = todos | ||
.filter(todo => todo.completed) | ||
.map(todo => todo.id); | ||
|
||
completedTodoId.forEach(todo => { | ||
handleDelete(todo); | ||
}); | ||
}; | ||
|
||
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"> | ||
{todos.length > 0 && ( | ||
<button | ||
type="button" | ||
className={classNames('todoapp__toggle-all', { | ||
active: todos.every(todo => todo.completed), | ||
})} | ||
data-cy="ToggleAllButton" | ||
onClick={completedAllTodos} | ||
/> | ||
)} | ||
|
||
<form onSubmit={handleSubmit}> | ||
<input | ||
value={newTodoTitle} | ||
ref={inputRef} | ||
onChange={e => setNewTodoTitle(e.target.value)} | ||
data-cy="NewTodoField" | ||
type="text" | ||
className={classNames('todoapp__new-todo', { | ||
focused: inputRef.current?.focus(), | ||
})} | ||
placeholder="What needs to be done?" | ||
disabled={tempTodo !== null} | ||
autoFocus | ||
/> | ||
</form> | ||
</header> | ||
|
||
<Todolist | ||
todos={filteredTodos} | ||
onToggleTodo={toggleTodoCompletion} | ||
onDelete={handleDelete} | ||
onUpdate={handleUpdateTodo} | ||
deletingId={deletingId} | ||
filteredTodos={filteredTodos} | ||
setErrorMessage={setErrorMessage} | ||
loadingIds={loadingIds} | ||
/> | ||
{tempTodo && ( | ||
<TodoItem | ||
todo={tempTodo} | ||
onDelete={handleDelete} | ||
onUpdate={handleUpdateTodo} | ||
deletingId={deletingId} | ||
filteredTodos={filteredTodos} | ||
setErrorMessage={setErrorMessage} | ||
loadingIds={loadingIds} | ||
/> | ||
)} | ||
{todos.length !== 0 && ( | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
<span className="todo-count" data-cy="TodosCounter"> | ||
{`${activeTodos} items left`} | ||
</span> | ||
|
||
<nav className="filter" data-cy="Filter"> | ||
{Object.values(FilterOptions).map(option => ( | ||
<a | ||
key={option} | ||
href={`#/${option}`} | ||
className={classNames('filter__link', { | ||
selected: currentFilter === option, | ||
})} | ||
data-cy={`FilterLink${option}`} | ||
onClick={() => setCurrentFilter(option)} | ||
> | ||
{option} | ||
</a> | ||
))} | ||
</nav> | ||
|
||
<button | ||
type="button" | ||
className="todoapp__clear-completed" | ||
data-cy="ClearCompletedButton" | ||
onClick={() => handleClearCompleted()} | ||
disabled={todos.every(todo => !todo.completed) || loading} | ||
> | ||
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('')} | ||
/> | ||
{errorMessage} | ||
</div> | ||
</div> | ||
</> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = 1806; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const postTodo = (newTodo: Omit<Todo, 'id'>): Promise<Todo> => { | ||
return client.post('/todos', newTodo); | ||
}; | ||
|
||
export const deleteTodos = (todoId: number) => { | ||
return client.delete(`/todos/${todoId}`); | ||
}; | ||
|
||
export const updateTodos = ({ id, userId, title, completed }: Todo) => { | ||
return client.patch(`/todos/${id}`, { userId, title, completed }); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Move this logic to the
Footer
component