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 #1501

Open
wants to merge 1 commit 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://dokrod.github.io/react_todo-app-with-api/) and add it to the PR description.
92 changes: 77 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,88 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useCallback, useState } from 'react';

import { Todo } from './types/Todo';

import { UserWarning } from './UserWarning';
import { USER_ID } from './api/todos';

const USER_ID = 0;
import { Footer } from './components/Footer';
import { Header } from './components/Header';
import { TodoItem } from './components/TodoItem';
import { ErrorNotification } from './components/ErrorNotification';
import { useTodos } from './components/hooks/useTodos';

export const App: React.FC = () => {
const {
todos,
errorMessage,
loadingTodosIds,
filteredTodos,
filter,
setTodos,
deleteTodo,
updateTodo,
toggleCompleted,
bulkToggleCompleted,
handleErrorMessage,
handleRemoveError,
handleFilterChange,
} = useTodos();
const [tempTodo, setTempTodo] = useState<Todo | null>(null);

const handleTempTodo = useCallback(
(todo: Todo | null) => {
setTempTodo(todo);
},
[setTempTodo],
);

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">
<Header
todos={todos}
setTodos={setTodos}
onError={handleErrorMessage}
setTempTodo={handleTempTodo}
bulkToggleCompleted={bulkToggleCompleted}
tempTodo={tempTodo}
/>

<section className="todoapp__main" data-cy="TodoList">
{filteredTodos.map(todo => (
<TodoItem
todo={todo}
loadingTodosIds={loadingTodosIds}
onDelete={deleteTodo}
onUpdate={updateTodo}
onChangeCompleted={toggleCompleted}
key={todo.id}
/>
))}
</section>

{tempTodo && (
<TodoItem todo={tempTodo} loadingTodosIds={loadingTodosIds} />
)}

{!!todos.length && (
<Footer
filterBy={filter}
setFilter={handleFilterChange}
todos={todos}
onDelete={deleteTodo}
/>
)}
</div>
<ErrorNotification
errorMessage={errorMessage}
handleRemoveError={handleRemoveError}
/>
</div>
);
};
34 changes: 34 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 1623;

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

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

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

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

export const todosService = {
getAll: getTodos,
create: createTodo,
delete: deleteTodo,
update: updateTodo,
};
30 changes: 30 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import cn from 'classnames';
import { ErrorType } from '../types/ErrorType';
import React from 'react';

type Props = {
errorMessage: ErrorType;
handleRemoveError: () => void;
};

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

type Props = {
todos: Todo[];
filterBy: FilterType;
setFilter: (filterBy: FilterType) => void;
onDelete: (todoId: number) => Promise<void>;
};

export const Footer: React.FC<Props> = ({
todos,
filterBy,
setFilter,
onDelete,
}) => {
const competedTodos = getFilteredTodos(todos, FilterType.completed);
const activeTodos = getFilteredTodos(todos, FilterType.active);

const filters = Object.values(FilterType);

const handleDeleteAllCompleted = () => {
competedTodos.map(todo => onDelete(todo.id));
};

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

<nav className="filter" data-cy="Filter">
{filters.map(filter => (
<a
href="#/"
className={cn('filter__link', {
selected: filterBy === filter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => setFilter(filter)}
key={filter}
>
{filter}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={handleDeleteAllCompleted}
disabled={!competedTodos.length}
>
Clear completed
</button>
</footer>
);
};
103 changes: 103 additions & 0 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import React, { useEffect, useRef, useState } from 'react';
import cn from 'classnames';

import { Todo } from '../types/Todo';
import { ErrorType } from '../types/ErrorType';
import { todosService, USER_ID } from '../api/todos';

type Props = {
todos: Todo[];
tempTodo: Todo | null;
setTodos: (updateTodos: (todos: Todo[]) => Todo[]) => void;
setTempTodo: (todo: Todo | null) => void;
onError: (error: ErrorType) => void;
bulkToggleCompleted: () => void;
};

export const Header: React.FC<Props> = ({
todos,
tempTodo,
setTodos,
onError,
setTempTodo,
bulkToggleCompleted,
}) => {
const [title, setTitle] = useState('');

const inputRef = useRef<HTMLInputElement>(null);

const allIsCompleted = todos.every(todo => todo.completed);

const handleChangeTitle = (event: React.ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value);
onError(ErrorType.DEFAULT);
};

const reset = () => {
setTitle('');
};

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

const normalizeTitle = title.trim();

if (!normalizeTitle) {
onError(ErrorType.TITLE);

return;
}

const newTodo = {
id: 0,
title: normalizeTitle,
userId: USER_ID,
completed: false,
};

setTempTodo(newTodo);

try {
const todo = await todosService.create(newTodo);

setTodos(currentTodos => [...currentTodos, todo]);
reset();
} catch {
onError(ErrorType.ADD);
setTempTodo(null);
} finally {
setTempTodo(null);
}
};

useEffect(() => {
inputRef.current?.focus();
}, [todos, tempTodo]);

return (
<header className="todoapp__header">
{!!todos.length && (
<button
type="button"
className={cn('todoapp__toggle-all', { active: allIsCompleted })}
data-cy="ToggleAllButton"
onClick={bulkToggleCompleted}
/>
)}

<form method="POST" onSubmit={handleSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
ref={inputRef}
value={title}
onChange={handleChangeTitle}
disabled={!!tempTodo}
autoFocus
/>
</form>
</header>
);
};
Loading
Loading