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

Implement todo update feature #798

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
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://OlhaMomot.github.io/react_todo-app-with-api/) and add it to the PR description.
74 changes: 56 additions & 18 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,62 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import React, {
useMemo,
useState,
} from 'react';
import { TodoList } from './components/TodoList';
import { Header } from './components/Header';
import { Todo } from './types/Todo';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { FilterOption } from './types/FilterOptions';
import { useTodo } from './hooks/useTodo';
import { getFilteredTodos } from './helpers/getFilteredTodos';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [filter, setFilter] = useState<string>(FilterOption.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);

const {
todos,
setErrorMessage,
errorMessage,
} = useTodo();

const filteredTodos = useMemo(
() => getFilteredTodos(todos, filter), [filter, todos],
);

const activeTodos = useMemo(() => {
return todos.filter(({ completed }) => !completed);
}, [todos]);

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
activeTodos={activeTodos}
setTempTodo={setTempTodo}
/>

{!!filteredTodos.length && (
<TodoList todos={filteredTodos} tempTodo={tempTodo} />
)}

{!!todos.length && (
<Footer
activeTodos={activeTodos}
filter={filter}
setFilter={setFilter}
/>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
/>
</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 addTodo = (newTodo: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', newTodo);
};

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

export const updateTodo = (todoId: number, newTodo: Omit<Todo, 'id'>) => {
return client.patch<Todo>(`/todos/${todoId}`, newTodo);
};
49 changes: 49 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import classNames from 'classnames';
import { useEffect } from 'react';

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

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => {
useEffect(() => {
let timer: NodeJS.Timeout | undefined;

if (errorMessage) {
timer = setTimeout(() => {
setErrorMessage('');
}, 3000);
}

return () => {
if (timer) {
clearTimeout(timer);
}
};
}, [errorMessage]);

return (
<div
data-cy="ErrorNotification"
className={
classNames(
'notification is-danger is-light has-text-weight-normal',

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
'notification is-danger is-light has-text-weight-normal',
'notification', 'is-danger', 'is-light', 'has-text-weight-normal',

{ hidden: !errorMessage },
)
}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage('')}
/>
{errorMessage}
</div>
);
};
66 changes: 66 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import classNames from 'classnames';
import React from 'react';

import { Todo } from '../types/Todo';
import { FilterOption } from '../types/FilterOptions';
import { useTodo } from '../hooks/useTodo';

type Props = {
activeTodos: Todo[],
filter: string,
setFilter: (filter: string) => void,
};

export const Footer: React.FC<Props> = ({
activeTodos,
filter,
setFilter,
}) => {
const { todos, handleDeleteTodo } = useTodo();

const completedTodos = todos.filter(({ completed }) => completed);

const onDeleteCompletedTodos = async () => {
await Promise.all(completedTodos
.map(({ id }) => handleDeleteTodo(id)));
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodos.length === 1
? '1 item left'
: `${activeTodos.length} items left`}
</span>

<nav className="filter" data-cy="Filter">
{Object.values(FilterOption).map((option) => (
<a
key={option}
data-cy={`FilterLink${option}`}
href={`#/${option.toLowerCase()}`}
className={classNames(
'filter__link',
{ selected: option === filter },
)}
onClick={() => setFilter(option)}
>
{option}
</a>
))}
</nav>

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

import { Todo } from '../types/Todo';
import { USER_ID } from '../utils/constants';
import { useTodo } from '../hooks/useTodo';

type Props = {
activeTodos: Todo[];
setTempTodo: (todo: Todo | null) => void;
};

export const Header: React.FC<Props> = ({ activeTodos, setTempTodo }) => {
const [title, setTitle] = useState('');
const [titleError, setTitleError] = useState(false);
const [isSubmiting, setIsSubmiting] = useState(false);
const todoTitleField = useRef<HTMLInputElement>(null);
const {
todos,
setErrorMessage,
handleAddTodo,
handleUpdateTodo,
} = useTodo();

useEffect(() => {
if (todoTitleField.current) {
todoTitleField.current.focus();
}
}, [todos.length]);

const onTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setTitle(event?.target.value);

if (titleError) {
setTitleError(false);
}
};

const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

setIsSubmiting(true);
const newTitle = title.trim();

if (!newTitle) {
setErrorMessage('Title should not be empty');
setIsSubmiting(false);

return;
}

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

setTempTodo({ id: 0, ...newTodo });

try {
await handleAddTodo(newTodo);

setIsSubmiting(false);

setTitle('');
setTempTodo(null);
} catch (error) {
setIsSubmiting(false);
setTempTodo(null);
}
};

const onToggleAll = async () => {
if (activeTodos.length) {
const updatePromises = activeTodos.map(currentTodo => handleUpdateTodo(
currentTodo,
{ completed: true },
));

await Promise.all(updatePromises);
} else {
const updatePromises = todos.map(currentTodo => handleUpdateTodo(
currentTodo,
{ completed: false },
));

await Promise.all(updatePromises);
}
};

return (
<header className="todoapp__header">
{!!todos.length
&& (
<button
type="button"
className={classNames(
'todoapp__toggle-all',
{ active: !activeTodos.length },
)}
data-cy="ToggleAllButton"
onClick={onToggleAll}
>
{' '}
</button>
)}
<form onSubmit={onSubmit}>
<input
ref={todoTitleField}
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={title}
onChange={onTitleChange}
disabled={isSubmiting}
/>
</form>
</header>
);
};
Loading
Loading