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 3 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.
81 changes: 64 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,71 @@
/* 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';

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(() => {
return todos.filter(({ completed }) => {
switch (filter) {
case FilterOption.Active:
return !completed;
case FilterOption.Completed:
return completed;
case FilterOption.All:
default:
return true;
}
});

Choose a reason for hiding this comment

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

I would move this logic to separate helper function

}, [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} />}

Choose a reason for hiding this comment

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

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


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

Choose a reason for hiding this comment

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

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

</div>
<ErrorNotification

Choose a reason for hiding this comment

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

Suggested change
</div>
<ErrorNotification
</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>
);
};
70 changes: 70 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import classNames from 'classnames';
import React, { useMemo } 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, deleteTodoHandler } = useTodo();

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

Choose a reason for hiding this comment

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

Suggested change
const completedTodos = useMemo(() => {
return todos.filter(({ completed }) => completed === true);
}, [todos]);
const completedTodos = todos.filter(({ completed }) => completed);

useMemo is useless here


const handleDeleteCompletedTodos = () => {
Promise.all(completedTodos
.map(({ id }) => deleteTodoHandler(id)));
};

Choose a reason for hiding this comment

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

Suggested change
const handleDeleteCompletedTodos = () => {
Promise.all(completedTodos
.map(({ id }) => deleteTodoHandler(id)));
};
const handleDeleteCompletedTodos = async () => {
await Promise.all(completedTodos.map(({ id }) =>
deleteTodoHandler(id)
));
};


const isClearButtonInvisible = completedTodos.length === 0;

Choose a reason for hiding this comment

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

Suggested change
const isClearButtonInvisible = completedTodos.length === 0;
const isClearButtonInvisible = !completedTodos.length;

But you don't really need variable for this


return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodos.length > 1
? `${activeTodos.length} items left`
: '1 item 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': isClearButtonInvisible,
})}
data-cy="ClearCompletedButton"
onClick={handleDeleteCompletedTodos}
disabled={isClearButtonInvisible}
>
Clear completed
</button>
</footer>
);
};
119 changes: 119 additions & 0 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
Copy link

Choose a reason for hiding this comment

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

let's fix this eslint issue:smiley:

try to work around aria-label , I think it can help

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,
addTodoHandler,
updateTodoHandler,
} = useTodo();

useEffect(() => {
if (todoTitleField.current) {
todoTitleField.current.focus();
}
});
Copy link

Choose a reason for hiding this comment

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

useEffect without a dependency array, is a bad practice

Currently, this useEffect triggers on every Header render, try to look at how it works on the mate demo.

I think there they focus input only after delete or add todo (after changing the amount of todos)


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

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

const handleSubmit = 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 addTodoHandler(newTodo);

setIsSubmiting(false);

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

const onToggleAll = async () => {
if (activeTodos.length) {
Promise.all(activeTodos
.map(currentTodo => updateTodoHandler(
currentTodo,
{ completed: true },
)));
} else {
Promise.all(todos
.map(currentTodo => updateTodoHandler(
currentTodo,
{ completed: false },
)));
}

Choose a reason for hiding this comment

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

DRY. a lot of code repeats, try to refactor this

Choose a reason for hiding this comment

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

Also add await before Promise.all

};

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