-
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
solved task #1486
Open
PikalovAndrey
wants to merge
7
commits into
mate-academy:master
Choose a base branch
from
PikalovAndrey: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
solved task #1486
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
229dedf
solved task
PikalovAndrey 4f8ed03
solved task with a small improvements
PikalovAndrey e7d5430
improved updateFunction
PikalovAndrey 088f77a
moved functions to another file and done rule "DRY"
PikalovAndrey 5ceb59d
solved task
PikalovAndrey 910e283
improve Errors components
PikalovAndrey bf1458d
Update README.md
PikalovAndrey 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,50 +1,42 @@ | ||
# React Todo App with API (complete) | ||
|
||
It is the third part of the React Todo App with API. | ||
|
||
Take your code implemented for [Add and Delete](https://github.com/mate-academy/react_todo-app-add-and-delete) | ||
and implement the ability to toggle and rename todos. | ||
|
||
> Here is [the working example](https://mate-academy.github.io/react_todo-app-with-api/) | ||
|
||
## Toggling a todo status | ||
|
||
Toggle the `completed` status on `TodoStatus` change: | ||
- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save. | ||
- covered the todo with a loader overlay while waiting for API response; | ||
- the status should be changed on success; | ||
- show the `Unable to update a todo` notification in case of API error. | ||
|
||
Add the ability to toggle the completed status of all the todos with the `toggleAll` checkbox: | ||
|
||
- `toggleAll` button should have `active` class only if all the todos are completed; | ||
- `toggleAll` click changes its status to the opposite one, and sets this new status to all the todos; | ||
- it should work the same as several individual updates of the todos which statuses were actually changed; | ||
- do send requests for the todos that were not changed; | ||
|
||
## Renaming a todo | ||
|
||
Implement the ability to edit a todo title on double click: | ||
|
||
- show the edit form instead of the title and remove button; | ||
- saves changes on the form submit (just press `Enter`); | ||
- save changes when the field loses focus (`onBlur`); | ||
- if the new title is the same as the old one just cancel editing; | ||
- cancel editing on `Esс` key `keyup` event; | ||
- if the new title is empty delete the todo the same way the `x` button does it; | ||
- if the title was changed show the loader while waiting for the API response; | ||
- update the todo title on success; | ||
- show `Unable to update a todo` in case of API error; | ||
- or the deletion error message if we tried to delete the todo. | ||
|
||
## If you want to enable tests | ||
- open `cypress/integration/page.spec.js` | ||
- replace `describe.skip` with `describe` for the root `describe` | ||
|
||
> ❗❗All tests should pass, even if some behaviour in not well explained in the task❗❗ | ||
## Demo | ||
- Link to Live Demo: [DEMO LINK](https://pikalovandrey.github.io/react_todo-app-with-api/) | ||
|
||
# React Todo App with API | ||
|
||
## Project Description | ||
This project implements the ability to toggle and rename tasks in a React-based Todo application. It focuses on enhancing user interaction with tasks while building upon the previously established functionalities of adding and deleting todos. | ||
|
||
## Achievements and Implemented Features | ||
|
||
### Toggling Todos | ||
- **Toggle Status**: Users can change the `completed` status of each todo item. | ||
- Added a loader overlay to indicate loading while waiting for the API response. | ||
- The todo status is updated upon successful API call. | ||
- Displays an error notification ("Unable to update a todo") in case of an API error. | ||
|
||
- **Toggle All**: A checkbox that allows users to toggle the completion status of all todos simultaneously. | ||
- The checkbox has an `active` class only if all todos are completed. | ||
- Clicking the checkbox changes its status and updates all todos accordingly. | ||
- The API sends requests only for the todos whose statuses actually changed. | ||
|
||
### Renaming Todos | ||
- **Edit on Double Click**: Users can rename a todo by double-clicking on it. | ||
- An edit form appears in place of the title and remove button. | ||
- Changes are saved on form submission (by pressing `Enter`) or when the field loses focus (`onBlur`). | ||
- If the new title matches the old one, editing is canceled. | ||
- Pressing `Esc` cancels the editing process. | ||
- If the new title is empty, the todo is deleted in the same way as with the remove button. | ||
- A loader is displayed while waiting for the API response upon title change. | ||
- Updates the todo title on success, with error notifications for any issues. | ||
|
||
## Technologies Used | ||
- React | ||
- TypeScript | ||
- CSS (Sass) | ||
- Axios for API calls | ||
|
||
## Instructions | ||
|
||
- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline). | ||
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript). | ||
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description. | ||
1. Clone the repository and navigate to the project directory. | ||
2. Install dependencies using `npm install`. | ||
3. Start the development server with `npm start`. | ||
4. Open the application in your browser at `http://localhost:3000`. |
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,87 @@ | ||
/* 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 React, { useEffect, useMemo, useState } from 'react'; | ||
import { FilterOptions, ErrorMessages } from './enums/'; | ||
import { filteredTodos, loadTodos } from './utils/'; | ||
import { Header, Footer, TodoList, Errors } from './components/'; | ||
import { useTodos } from './hooks/useTodos'; | ||
|
||
export const App: React.FC = () => { | ||
if (!USER_ID) { | ||
return <UserWarning />; | ||
} | ||
const [filter, setFilter] = useState<FilterOptions>(FilterOptions.ALL); | ||
const [errorMessage, setErrorMessage] = useState(ErrorMessages.NO_ERRORS); | ||
|
||
const { | ||
todos, | ||
tempTodo, | ||
loadingTodosCount, | ||
inputRef, | ||
inputValue, | ||
handleSubmit, | ||
handleUpdateTodo, | ||
handleTodoDelete, | ||
setTodos, | ||
handleTodosToggle, | ||
handleTodoToggle, | ||
handleCompletedTodosDeleted, | ||
handleInputChange, | ||
} = useTodos(setErrorMessage); | ||
|
||
const todosAfterFiltering = useMemo( | ||
() => filteredTodos(todos, filter), | ||
[todos, filter], | ||
); | ||
|
||
const completedTodos = useMemo( | ||
() => todos.filter(todo => todo.completed), | ||
[todos], | ||
); | ||
|
||
useEffect(() => { | ||
if (inputRef.current) { | ||
inputRef.current.focus(); | ||
} | ||
}, [todos, inputRef]); | ||
|
||
useEffect(() => { | ||
loadTodos(setTodos, setErrorMessage); | ||
}, [setTodos]); | ||
|
||
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 | ||
value={inputValue} | ||
todos={todos} | ||
completedTodos={completedTodos} | ||
inputRef={inputRef} | ||
loadingTodos={loadingTodosCount} | ||
onTodosToggle={handleTodosToggle} | ||
onSubmit={handleSubmit} | ||
onInputChange={handleInputChange} | ||
/> | ||
|
||
<TodoList | ||
tempTodo={tempTodo} | ||
todosAfterFiltering={todosAfterFiltering} | ||
loadingTodos={loadingTodosCount} | ||
inputRef={inputRef} | ||
onTodoDelete={handleTodoDelete} | ||
onTodoToggle={handleTodoToggle} | ||
onUpdateTodo={handleUpdateTodo} | ||
/> | ||
|
||
{!!todos.length && ( | ||
<Footer | ||
todos={todos} | ||
completedTodos={completedTodos} | ||
filter={filter} | ||
setFilter={setFilter} | ||
onCompletedTodosDeleted={handleCompletedTodosDeleted} | ||
/> | ||
)} | ||
</div> | ||
|
||
<Errors errorMessage={errorMessage} setErrorMessage={setErrorMessage} /> | ||
</div> | ||
); | ||
}; |
This file was deleted.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { Todo } from '../types/Todo'; | ||
import { client } from '../utils/fetchClient'; | ||
import { USER_ID } from '../utils/USER_ID'; | ||
|
||
export const getTodos = () => { | ||
return client.get<Todo[]>(`/todos?userId=${USER_ID}`); | ||
}; | ||
|
||
export const deleteTodos = (todoId: number): Promise<void> => { | ||
return client.delete(`/todos/${todoId}`).then(() => {}); | ||
}; | ||
|
||
export const addTodo = (newTodo: Omit<Todo, 'id'>): Promise<Todo> => { | ||
return client.post('/todos', newTodo); | ||
}; | ||
|
||
export const changeTodo = ( | ||
todoId: number, | ||
updatedFields?: Partial<Todo>, | ||
): Promise<void> => { | ||
return client.patch(`/todos/${todoId}`, updatedFields); | ||
}; |
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,38 @@ | ||
import classNames from 'classnames'; | ||
import { ErrorMessages } from '../enums/ErrorMessages'; | ||
import { Dispatch, FC, SetStateAction, useEffect } from 'react'; | ||
|
||
interface ErrorsProps { | ||
errorMessage: ErrorMessages; | ||
setErrorMessage: Dispatch<SetStateAction<ErrorMessages>>; | ||
} | ||
|
||
export const Errors: FC<ErrorsProps> = ({ errorMessage, setErrorMessage }) => { | ||
useEffect(() => { | ||
if (errorMessage) { | ||
const timer = setTimeout(() => { | ||
setErrorMessage(ErrorMessages.NO_ERRORS); | ||
}, 3000); | ||
|
||
return () => clearTimeout(timer); | ||
} | ||
}, [errorMessage, setErrorMessage]); | ||
|
||
return ( | ||
<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(ErrorMessages.NO_ERRORS)} | ||
/> | ||
{errorMessage} | ||
</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,57 @@ | ||
import classNames from 'classnames'; | ||
import { Todo } from '../types/Todo'; | ||
import { FilterOptions } from '../enums/FilterOptions'; | ||
import { Dispatch, FC, SetStateAction } from 'react'; | ||
|
||
interface FooterProps { | ||
todos: Todo[]; | ||
completedTodos: Todo[]; | ||
filter: FilterOptions; | ||
setFilter: Dispatch<SetStateAction<FilterOptions>>; | ||
onCompletedTodosDeleted: () => void; | ||
} | ||
|
||
export const Footer: FC<FooterProps> = ({ | ||
todos, | ||
completedTodos, | ||
filter, | ||
setFilter, | ||
onCompletedTodosDeleted, | ||
}) => { | ||
const atLeastOneIsActive = todos.some(todo => todo.completed); | ||
const leftTodos = todos.length - completedTodos.length; | ||
|
||
return ( | ||
<footer className="todoapp__footer" data-cy="Footer"> | ||
<span className="todo-count" data-cy="TodosCounter"> | ||
{leftTodos} items left | ||
</span> | ||
|
||
<nav className="filter" data-cy="Filter"> | ||
{Object.values(FilterOptions).map(filterOption => ( | ||
<a | ||
key={filterOption} | ||
href={`#/${filterOption.charAt(0).toUpperCase() + filterOption.slice(1)}`} | ||
className={classNames('filter__link', { | ||
selected: filter === filterOption, | ||
})} | ||
data-cy={`FilterLink${filterOption.charAt(0).toUpperCase() + filterOption.slice(1)}`} | ||
onClick={() => setFilter(filterOption)} | ||
> | ||
{filterOption.charAt(0).toUpperCase() + filterOption.slice(1)} | ||
</a> | ||
))} | ||
</nav> | ||
|
||
<button | ||
type="button" | ||
className="todoapp__clear-completed" | ||
data-cy="ClearCompletedButton" | ||
onClick={onCompletedTodosDeleted} | ||
disabled={!atLeastOneIsActive} | ||
> | ||
Clear completed | ||
</button> | ||
</footer> | ||
); | ||
}; |
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,55 @@ | ||||||
import classNames from 'classnames'; | ||||||
import { Todo } from '../types/Todo'; | ||||||
import { FormEvent } from 'react'; | ||||||
|
||||||
interface HeaderProps { | ||||||
value: string; | ||||||
todos: Todo[]; | ||||||
completedTodos: Todo[]; | ||||||
inputRef: React.RefObject<HTMLInputElement>; | ||||||
loadingTodos: number[]; | ||||||
onTodosToggle: () => void; | ||||||
onSubmit: (event: FormEvent<HTMLFormElement>) => void; | ||||||
onInputChange: (event: React.ChangeEvent<HTMLInputElement>) => void; | ||||||
} | ||||||
|
||||||
export const Header: React.FC<HeaderProps> = ({ | ||||||
value, | ||||||
todos, | ||||||
completedTodos, | ||||||
inputRef, | ||||||
loadingTodos, | ||||||
onTodosToggle, | ||||||
onSubmit, | ||||||
onInputChange, | ||||||
}) => { | ||||||
const isLoading = loadingTodos.length > 0; | ||||||
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
|
||||||
|
||||||
return ( | ||||||
<header className="todoapp__header"> | ||||||
{!!todos.length && ( | ||||||
<button | ||||||
type="button" | ||||||
className={classNames('todoapp__toggle-all', { | ||||||
active: completedTodos.length === todos.length, | ||||||
})} | ||||||
data-cy="ToggleAllButton" | ||||||
onClick={onTodosToggle} | ||||||
/> | ||||||
)} | ||||||
|
||||||
<form onSubmit={onSubmit}> | ||||||
<input | ||||||
data-cy="NewTodoField" | ||||||
type="text" | ||||||
className="todoapp__new-todo" | ||||||
placeholder="What needs to be done?" | ||||||
value={value} | ||||||
ref={inputRef} | ||||||
onChange={onInputChange} | ||||||
disabled={isLoading} | ||||||
/> | ||||||
</form> | ||||||
</header> | ||||||
); | ||||||
}; |
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.
In my opinion, it's rather confusing. Part of the logic associated with todo is in the custom hook, and the other part is spread across components. It is better to either put everything in the hook or not use it at all.
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.
Good point!