Skip to content
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://Nika-Andriy.github.io/react_todo-app-with-api/) and add it to the PR description.
191 changes: 176 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,187 @@
/* 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, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { deleteTodo, getTodos, patchTodo, USER_ID } from './api/todos';
import { NewTodoList } from './components/NewTodoList';
import { Todo } from './types/Todo';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { FILTER } from './api/filter';
import { Filter } from './types/Filter';
import { TodoItem } from './components/TodoItem';
import { ErrorMessage } from './types/ErrorMessage';
import { ErrorNotification } from './components/ErrorNotification';

export const App: React.FC = () => {
const [title, setTitle] = useState('');
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [filter, setFilter] = useState<Filter>(FILTER.all);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [deletingTodoIds, setDeletingTodoIds] = useState<number[]>([]);
const [updatingTodoIds, setUpdatingTodoIds] = useState<number[]>([]);

const isTodosNotEmpty = todos.length > 0;

const loadingPosts = () => {
setIsLoading(true);

getTodos()
.then(setTodos)
.catch(() => setErrorMessage(ErrorMessage.LOAD_TODO))
.finally(() => setIsLoading(false));
};

useEffect(() => {
loadingPosts();
}, []);

useEffect(() => {
if (!errorMessage) {
return;
}

const timerId = window.setTimeout(() => {
setErrorMessage('');
}, 3000);

return () => window.clearTimeout(timerId);
}, [errorMessage]);

const getVisibleTodos = () => {
switch (filter) {
case FILTER.active:
return todos.filter(todo => !todo.completed);

case FILTER.completed:
return todos.filter(todo => todo.completed);

default:
return todos;
}
};

const visibleTodos = getVisibleTodos();

const handleDelete = (todoId: number) => {
setIsDeleting(true);
setDeletingTodoIds(ids => [...ids, todoId]);

return deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.DELETE_TODO);
throw new Error();
})
.finally(() => {
setIsDeleting(false);
setDeletingTodoIds(ids => ids.filter(id => id !== todoId));
});
};

const updateTodo = (todo: Todo, newTodo: Todo) => {
setUpdatingTodoIds(ids => [...ids, todo.id]);

return patchTodo(newTodo)
.then(() => {
setTodos(current =>
current.map(item => (item.id === todo.id ? newTodo : item)),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.UPDATE_TODO);
throw new Error();
})
.finally(() => {
setUpdatingTodoIds(ids => ids.filter(id => id !== todo.id));
});
};

const handleChecked = (todo: Todo) => {
updateTodo(todo, {
...todo,
completed: !todo.completed,
});
};

const handleToggleAll = (posts: Todo[]) => {
const areAllTodosCompleted = posts.every(t => t.completed);

if (!areAllTodosCompleted) {
posts.forEach(t => {
if (!t.completed) {
handleChecked(t);
}
});
} else {
posts.forEach(t => {
if (t.completed) {
handleChecked(t);
}
});
}
};

const handleHideErrorMessage = () => {
setErrorMessage('');
};

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">
<NewTodoList
todos={todos}
title={title}
isLoading={isLoading}
isDeleting={isDeleting}
setTitle={setTitle}
setTodos={setTodos}
setErrorMessage={setErrorMessage}
setIsLoading={setIsLoading}
setTempTodo={setTempTodo}
onToggleAll={handleToggleAll}
/>

<section className="todoapp__main" data-cy="TodoList">
<TodoList
todos={visibleTodos}
deletingTodoIds={deletingTodoIds}
updatingTodoIds={updatingTodoIds}
setErrorMessage={setErrorMessage}
updateTodo={updateTodo}
onDelete={handleDelete}
onChecked={handleChecked}
/>
{tempTodo && <TodoItem todo={tempTodo} isLoading />}
</section>

{isTodosNotEmpty && (
<Footer
todos={todos}
filter={filter}
setFilter={setFilter}
onDelete={handleDelete}
/>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
onHide={handleHideErrorMessage}
/>
</div>
);
};
5 changes: 5 additions & 0 deletions src/api/filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const FILTER = {
all: 'all',
completed: 'completed',
active: 'active',
} as const;
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 USER_ID = 4198;

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

// Add more methods here
export const patchTodo = ({ id, ...todoData }: Todo) => {
return client.patch<Todo>(`/todos/${id}`, todoData);
};

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

export const deleteTodo = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};
33 changes: 33 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from 'react';
import classNames from 'classnames';

type Props = {
errorMessage: string;
onHide: () => void;
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
onHide,
}) => {
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"
aria-label="Hide error notification"
onClick={onHide}
/>
{errorMessage}
</div>
);
};
80 changes: 80 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React from 'react';
import { Todo } from '../types/Todo';
import { Filter } from '../types/Filter';
import classNames from 'classnames';
import { FILTER } from '../api/filter';

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

export const Footer: React.FC<Props> = ({
todos,
filter,
setFilter,
onDelete,
}) => {
const activeTodos = todos.filter(todo => !todo.completed);
const completedTodos = todos.filter(todo => todo.completed);
const isCompletedTodos = todos.some(todo => todo.completed);

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

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
<a
href="#/"
className={classNames('filter__link', {
selected: filter === FILTER.all,
})}
data-cy="FilterLinkAll"
onClick={() => setFilter(FILTER.all)}
>
All
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: filter === FILTER.active,
})}
data-cy="FilterLinkActive"
onClick={() => setFilter(FILTER.active)}
>
Active
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: filter === FILTER.completed,
})}
data-cy="FilterLinkCompleted"
onClick={() => setFilter(FILTER.completed)}
>
Completed
</a>
</nav>

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