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

Solution #1580

Open
wants to merge 3 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ Implement the ability to edit a todo title on double click:

- 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.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://AndreaTkachuk.github.io/react_todo-app-with-api/) and add it to the PR description.
248 changes: 232 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,242 @@
/* 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 { UserWarning } from './UserWarning';

const USER_ID = 0;
import React, { useEffect, useState } from 'react';
import { UserWarning } from './components/UserWarning';
import {
getTodos,
postTodo,
removeTodo,
renewTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { ErrorComponent } from './components/ErrorComponent';
import { Footer } from './components/Footer';
import { getFilteredItems } from './utils/getFilteredItems';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Filter } from './utils/enamFilter';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [filter, setFilter] = useState<Filter>(Filter.All);
const [error, setError] = useState('');
const [title, setTitle] = useState('');
const [loading, setLoading] = useState<number | null>(null);
const [isEditingId, setIsEditingId] = useState<number | null>(null);
const showError = (message: string) => {
setError(message);

setTimeout(() => {
setError('');
}, 3000);
};

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => showError('Unable to load todos'))
.finally(() => setLoading(0));
}, []);

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

const addTodo = (todoTitle: string) => {
setLoading(1);
setTempTodo({
id: 0,
userId: 2215,
title: todoTitle,
completed: false,
});

postTodo(title.trim())
.then((newTodo: Todo) => {
setTodos(prevTodos => [...prevTodos, newTodo]);
setError('');
setTitle('');
})
.catch(() => showError('Unable to add a todo'))
.finally(() => {
setLoading(0);
setTempTodo(null);
});
};

const updateTodoCheck = (id: number) => {
setLoading(id);

const todoToUpdate = todos.find(todo => todo.id === id);

if (!todoToUpdate) {
setLoading(0);

return;
}

const updatedTodo = {
...todoToUpdate,
completed: !todoToUpdate.completed,
};

renewTodo(id, updatedTodo)
.then(() => {
setTodos(currentTodos =>
currentTodos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo,
),
);
setLoading(0);
})
.catch(() => showError('Unable to update a todo'))
.finally(() => setLoading(0));
};

const updateTodoTitle = (id: number, value: string): Promise<void> | void => {
if (loading === id) {
return;
}

setLoading(id);

const todoToUpdate = todos.find(todo => todo.id === id);

if (!todoToUpdate) {
setLoading(0);

return;
}

if (value === todoToUpdate.title) {
setIsEditingId(null);
setLoading(0);

return;
}

const updatedTodo = {
...todoToUpdate,
title: value,
};

return renewTodo(id, updatedTodo)
.then(() => {
setTodos(currentTodos =>
currentTodos.map(todo =>
todo.id === id ? { ...todo, title: value } : todo,
),
);
setLoading(0);
})
.catch(nextError => {
setLoading(0);
showError('Unable to update a todo');
throw nextError;
});
};

const deleteTodo = (id: number): Promise<void> | void => {
setLoading(id);

removeTodo(id)
.then(() => {
setTodos(todos.filter(item => item.id !== id));
setLoading(0);
})
.catch(() => {
showError('Unable to delete a todo');
setLoading(0);
});
};

const clearCompleted = () => {
const todosCompleted = todos.filter(todo => todo.completed);
const successIds: number[] = [];

Promise.all(
todosCompleted.map(todo => {
setLoading(todo.id);

return removeTodo(todo.id)
.then(() => successIds.push(todo.id))
.catch(() => showError('Unable to delete a todo'));
}),
)
.then(() => {
setTodos(todos.filter(todo => !successIds.includes(todo.id)));
})
.catch(() => showError('Unable to delete a todo'))
.finally(() => setLoading(0));
};

const toggleAllTodos = () => {
const areAllTodosCompleted = todos.every(todo => todo.completed);

const todosToToggle = areAllTodosCompleted
? todos
: todos.filter(todo => !todo.completed);

Promise.all(
todosToToggle.map(todo =>
renewTodo(todo.id, { ...todo, completed: !areAllTodosCompleted })
.then(() => {
setTodos(currentTodos =>
currentTodos.map(t =>
t.id === todo.id
? { ...t, completed: !areAllTodosCompleted }
: t,
),
);
})
.catch(() => showError(`Unable to toggle todo with id ${todo.id}`)),
),
).finally(() => setLoading(0));
};

const filteredTodos = getFilteredItems(todos, filter);

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
todos={todos}
addTodo={addTodo}
toggleAllTodos={toggleAllTodos}
setError={setError}
showError={showError}
loading={loading}
title={title}
setTitle={setTitle}
isEditingId={isEditingId}
/>

<TodoList
setError={setError}
filteredTodos={filteredTodos}
loading={loading}
deleteTodo={deleteTodo}
updateTodoCheck={updateTodoCheck}
updateTodoTitle={updateTodoTitle}
tempTodo={tempTodo}
isEditingId={isEditingId}
setIsEditingId={setIsEditingId}
/>

{todos.length > 0 && (
<Footer
todos={todos}
filter={filter}
setFilter={setFilter}
clearCompleted={clearCompleted}
/>
)}
</div>
<ErrorComponent error={error} onClose={() => setError('')} />
</div>
);
};
27 changes: 27 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 2215;

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

export const postTodo = (value: string) => {
const newTodo = {
title: value,
completed: false,
};

return client.post<Todo>(`/todos`, { ...newTodo, userId: USER_ID });
};

export const renewTodo = (id: number, updatedTodo: Todo) => {
return client.patch<Todo>(`/todos/${id}`, updatedTodo);
};

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

// Add more methods here
27 changes: 27 additions & 0 deletions src/components/ErrorComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import classNames from 'classnames';
import React from 'react';

type Props = {
error: string;
onClose: () => void;
};

export const ErrorComponent: React.FC<Props> = ({ error, onClose }) => {
return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: !error },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>
{error}
</div>
);
};
56 changes: 56 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React from 'react';
import { Todo } from '../types/Todo';
import classNames from 'classnames';
import { Filter } from '../utils/enamFilter';

type Props = {
todos: Todo[];
filter: Filter;
setFilter: (filter: Filter) => void;
clearCompleted: () => void;
};

export const Footer: React.FC<Props> = ({
todos,
filter,
setFilter,
clearCompleted,
}) => {
const leftItems = todos.filter(todo => !todo.completed).length;

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{leftItems} items left
</span>

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
{Object.keys(Filter).map(key => (
<a
key={key}
href={`#/${key}`}
className={classNames('filter__link', {
selected: filter === key.toLowerCase(),
})}
data-cy={`FilterLink${key}`}
onClick={() => setFilter(key.toLowerCase() as Filter)}
>
{key}
</a>
))}
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={clearCompleted}
disabled={todos.every(todo => !todo.completed)}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading