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

Develop Todo app with api #717

Open
wants to merge 2 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 @@ -41,4 +41,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://taras-bilas.github.io/react_todo-app-with-api/) and add it to the PR description.
176 changes: 164 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,176 @@
/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { UserWarning } from './UserWarning';
import { TodoHeader } from './components/TodoHeader';
import { TodoList } from './components/TodoList';
import { TodoItem } from './components/TodoItem';
import { TodoFooter } from './components/TodoFooter';
import { deleteTodos, getTodos, updateTodos } from './api/todos';
import { Todo } from './types/Todo';
import { Status } from './types/Status';
import { Error } from './types/Error';
import { Errors } from './components/Errors';

const USER_ID = 0;
const USER_ID = 11142;

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [status, setStatus] = useState(Status.all);
const [error, setError] = useState(Error.without);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [deletingIds, setDeletingIds] = useState<number[]>([]);
const [processing, setProcessing] = useState(false);
const numberOfAllTodos = todos.length;
const numberOfCompletedTodos = todos.filter(todo => todo.completed).length;
const numberOfActiveTodos = todos.filter(todo => !todo.completed).length;
const areAllCompleted = todos.every(todo => todo.completed);

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

const toggleTodo = useCallback((todo: Todo) => {
const changedStatus = { completed: !todo.completed };

setDeletingIds((ids) => [...ids, todo.id]);

updateTodos(todo.id, changedStatus)
.then(() => {
return getTodos(USER_ID)
.then(setTodos)
.catch(() => setError(Error.load));
})
.catch(() => setError(Error.update))
.finally(() => {
setDeletingIds((ids) => ids.filter(id => id !== todo.id));
});
}, [todos]);

const toggleAll = () => {
if (areAllCompleted) {
todos.forEach(todo => {
toggleTodo(todo);
});
}

todos
.filter(todo => !todo.completed)
.forEach(todo => toggleTodo(todo));
};

const renameTodo = useCallback((todoId: number, newTitle: string) => {
if (newTitle.trim().length === 0) {
setError(Error.update);

return;
}

const newData = { title: newTitle };

setDeletingIds((ids) => [...ids, todoId]);

updateTodos(todoId, newData)
.then(() => {
return getTodos(USER_ID)
.then(setTodos)
.catch(() => setError(Error.load));
})
.catch(() => {
setError(Error.update);
})
.finally(() => {
setDeletingIds((ids) => ids.filter(id => id !== todoId));
});
}, [todos]);

const deleteTodo = useCallback((todoId: number) => {
setDeletingIds((ids) => [...ids, todoId]);

deleteTodos(todoId)
.then(() => setTodos(
currentTodos => currentTodos.filter(todo => todo.id !== todoId),
))
.catch(() => setError(Error.delete))
.finally(() => {
setDeletingIds((ids) => ids.filter(id => id !== todoId));
});
}, [todos]);

const visibleTodos = useMemo(() => {
if (todos) {
return todos
.filter(todo => {
switch (status) {
case Status.completed:
return todo.completed;

case Status.active:
return !todo.completed;

default:
return true;
}
});
}

return [];
}, [todos, status]);

if (!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
userId={USER_ID}
setTempTodo={setTempTodo}
setError={setError}
setTodos={setTodos}
processing={processing}
setProcessing={setProcessing}
areAllCompleted={areAllCompleted}
toggleAll={toggleAll}
/>

{numberOfAllTodos !== 0 && (
<TodoList
todos={visibleTodos}
toggleTodo={toggleTodo}
onRenameTodo={renameTodo}
onDeleteTodo={deleteTodo}
deletingIds={deletingIds}
/>
)}

{tempTodo && (
<TodoItem
tempTodo={tempTodo}
processing={processing}
/>
)}

{numberOfAllTodos !== 0 && (
<TodoFooter
numberOfActiveTodos={numberOfActiveTodos}
numberOfCompletedTodos={numberOfCompletedTodos}
onStatusChange={setStatus}
status={status}
onDeleteTodo={deleteTodo}
todos={todos}
/>
)}
</div>

{error !== Error.without && (
<Errors error={error} onClearErrors={setError} />
)}
</div>
);
};
18 changes: 18 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

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

export const addTodos = (userId: number, data: any) => {
return client.post<Todo[]>(`/todos?userId=${userId}`, data);
};

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

export const updateTodos = (todoId: number, data: any) => {
return client.patch(`/todos/${todoId}`, data);
};
41 changes: 41 additions & 0 deletions src/components/Errors.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
/* eslint-disable quote-props */
import { useEffect } from 'react';
import cn from 'classnames';
import { Error } from '../types/Error';

type Props = {
error: Error,
onClearErrors: React.Dispatch<React.SetStateAction<Error>>,
};

export const Errors: React.FC<Props> = ({ error, onClearErrors }) => {
useEffect(() => {
setTimeout(() => onClearErrors(Error.without), 3000);
}, [error]);

return (
<div
className={cn(
'notification is-danger is-light has-text-weight-normal',
{ 'hidden': error === Error.without },
)}
>
<button
type="button"
className="delete"
onClick={() => onClearErrors(Error.without)}
/>

{error === Error.load && 'Unable to load todos'}

{error === Error.add && 'Unable to add a todo'}

{error === Error.delete && 'Unable to delete a todo'}

{error === Error.update && 'Unable to update a todo'}

{error === Error.empty && 'Title can\'t be empty'}
</div>
);
};
85 changes: 85 additions & 0 deletions src/components/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/* eslint-disable quote-props */
import cn from 'classnames';
import { Status } from '../types/Status';
import { Todo } from '../types/Todo';

type Props = {
numberOfActiveTodos: number,
numberOfCompletedTodos: number,
onStatusChange: React.Dispatch<React.SetStateAction<Status>>,
status: Status,
onDeleteTodo: (todoId: number) => void,
todos: Todo[],
};

export const TodoFooter: React.FC<Props> = ({
numberOfActiveTodos,
numberOfCompletedTodos,
onStatusChange,
status,
onDeleteTodo,
todos,
}) => {
const deleteCompleted = () => {
todos.filter(todo => todo.completed).forEach((todo) => {
onDeleteTodo(todo.id);
});
};

return (
<footer className="todoapp__footer">
<span className="todo-count">
{numberOfActiveTodos}
{' '}
items left
</span>

<nav className="filter">
<a
href="#/"
className={cn(
'filter__link',
{ 'selected': status === Status.all },
)}
onClick={() => onStatusChange(Status.all)}
>
All
</a>

<a
href="#/active"
className={cn(
'filter__link',
{ 'selected': status === Status.active },
)}
defaultValue={Status.active}
onClick={() => onStatusChange(Status.active)}
>
Active
</a>

<a
href="#/completed"
className={cn(
'filter__link',
{ 'selected': status === Status.completed },
)}
defaultValue={Status.completed}
onClick={() => onStatusChange(Status.completed)}
>
Completed
</a>
</nav>

{numberOfCompletedTodos !== 0 && (
<button
type="button"
className="todoapp__clear-completed"
onClick={deleteCompleted}
>
Clear completed
</button>
)}
</footer>
);
};
Loading