Skip to content
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

add task solution #770

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 9 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,12 @@
# React Todo App with API (complete)
# React Todo App

It is the third part of the React Todo App with API.
Technologies used:
- HTML
- CSS
- TypeScript
- React

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.
[DEMO](https://annaviolin23.github.io/react_todo-app-with-api/)

> 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:

- 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.

## 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.
How to use:
[VIDEO](https://drive.google.com/file/d/1nH5oAgHemgwnzW3182qW7n5eMOEOigzH/view?usp=sharing)
2 changes: 2 additions & 0 deletions public/icons/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ToDo App</title>
<link rel="icon" type="image/x-icon" href="./icons/favicon.svg">
</head>
<body>
<div id="root"></div>
Expand Down
262 changes: 250 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,262 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, {
FormEvent, useEffect, useMemo, useState,
} from 'react';
import classNames from 'classnames';
import { Todo } from './types/Todo';
import { FilterType } from './types/FilterTypes';
import { Error } from './utils/errorUtils';
import { getTodos } from './api/todos';
import * as postService from './api/todos';
import { UserWarning } from './UserWarning';
import { TodoList } from './components/TodoList';
import { TodoFilter } from './components/FilterTodo';
import { TodoError } from './components/TodoError';
import { TodoItem } from './components/TodoItem';

const USER_ID = 0;
const USER_ID = 11707;

const getVisibleTodos = (todos: Todo[], status: FilterType) => {
return todos.filter(todo => {
switch (status) {
case FilterType.Completed:
return todo.completed;

case FilterType.Active:
return !todo.completed;

default:
return true;
}
});
};

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [status, setStatus] = useState(FilterType.All);
const [errorMessage, setErrorMessage] = useState(Error.None);
const [query, setQuery] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingIds, setLoadingIds] = useState<number[]>([]);

useEffect(() => {
getTodos(USER_ID)
.then(setTodos)
.catch(() => setErrorMessage(Error.Load));
}, []);

const visibleTodos = useMemo(() => getVisibleTodos(todos, status),
[todos, status]);

const todosCount = useMemo(() => todos.filter(todo => !todo.completed).length,
[todos]);

const isCompletedTodos = useMemo(() => todos.some(todo => todo.completed),
[todos]);

const completedTodoCount = todos.filter(todo => todo.completed).length;

const handleQuery = (event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
};

const handleSubmit = (event: FormEvent) => {
event.preventDefault();

if (query.trim() === '') {
setErrorMessage(Error.EmptyTitle);

return;
}

const newTodo = {
title: query,
completed: false,
userId: USER_ID,
};

setTempTodo({ ...newTodo, id: 0 });
setLoadingIds((ids) => [...ids, 0]);

postService.createTodo(newTodo)
.then((value) => {
setTodos(currentTodos => [...currentTodos, value]);
setTempTodo(null);
})
.catch((error) => {
setErrorMessage(Error.Add);
throw error;
})
.finally(() => {
setLoadingIds((ids) => ids.filter(id => id !== 0));
});

setQuery('');
};

const onDeleteTodo = (todoId: number) => {
setLoadingIds((ids) => [...ids, todoId]);
postService.deleteTodo(todoId)
.then(() => setTodos(
currentTodos => currentTodos.filter(
todo => todo.id !== todoId,
),
))
.catch(() => setErrorMessage(Error.Delete))
.finally(() => setLoadingIds((ids) => ids.filter(id => id !== todoId)));
};

const onDeleteCompleted = () => {
todos.filter(todo => todo.completed).forEach((todo) => {
onDeleteTodo(todo.id);
});
};

if (!USER_ID) {
return <UserWarning />;
}

const handleToggleAll = () => {
const uncompletedTodos = todos.filter(todo => !todo.completed);
const uncompletedTodosIds = uncompletedTodos.map(todo => todo.id);

if (uncompletedTodos.length === 0) {
setLoadingIds(currentIds => [
...currentIds,
...todos.map(
todo => todo.id,
)]);

Promise.all(todos.map(todo => {
return postService.updateTodo(todo.id, {
completed: !todo.completed,
});
}))
.then(() => {
getTodos(USER_ID)
.then((value) => {
setTodos(value);
setLoadingIds([]);
})
.catch(() => {
setErrorMessage(Error.Load);
});
})
.catch(() => {
setErrorMessage(Error.Update);
});

return;
}

setLoadingIds(currentIds => [...currentIds, ...uncompletedTodosIds]);

Promise.all(uncompletedTodos.map(todo => {
return postService.updateTodo(todo.id, {
completed: !todo.completed,
});
}))
.then(() => {
getTodos(USER_ID)
.then((value) => {
setTodos(value);
})
.catch(() => {
setErrorMessage(Error.Load);
})

.finally(() => {
setLoadingIds([]);
});
})
.catch(() => {
setErrorMessage(Error.Update);
});
};

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: completedTodoCount !== 0,
})}
onClick={handleToggleAll}
/>
)}

<form onSubmit={(event) => handleSubmit(event)}>
<input
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={query}
onChange={handleQuery}
/>
</form>
</header>

{!!todos.length && (
<>
<TodoList
todos={visibleTodos}
onDeleteTodo={onDeleteTodo}
loadingIds={loadingIds}
setTodos={setTodos}
setLoadingIds={setLoadingIds}
/>

{tempTodo && (
<TodoItem
todo={tempTodo}
onDeleteTodo={onDeleteTodo}
loadingIds={loadingIds}
setTodos={setTodos}
setLoadingIds={setLoadingIds}
todos={visibleTodos}
/>
)}

<footer className="todoapp__footer">
<span className="todo-count">
{todosCount === 1 ? ('1 item left')
: (`${todosCount} items left`)}
</span>

<TodoFilter
status={status}
onStatusChange={setStatus}
/>

<button
type="button"
className={classNames(
'todoapp__clear-completed',
{ 'todoapp__clear-completed--disabled': !isCompletedTodos },
)}
onClick={onDeleteCompleted}
>
Clear completed
</button>
</footer>
</>
)}
</div>

{
errorMessage && (
<TodoError
error={errorMessage}
onErrorChange={setErrorMessage}
/>
)
}
</div>
);
};
21 changes: 21 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const getTodos = (userId: number) => {
return client.get<Todo[]>(`/todos?userId=${userId}`);
};

export const createTodo = ({ title, completed, userId }: Omit <Todo, 'id'>) => {
return client.post<Todo>('/todos', { title, completed, userId });
};

export const deleteTodo = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};

export const updateTodo = (
todoId: number,
data: { completed?: boolean, title?: string },
) => {
return client.patch(`/todos/${todoId}`, data);
};
Loading