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 editing functionality #778

Open
wants to merge 8 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
57 changes: 39 additions & 18 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,45 @@
/* 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, { useContext, useEffect, useState } from 'react';
import { TodoHeader } from './components/TodoHeader';
import { TodoList } from './components/TodoList';
import { TodoFooter } from './components/TodoFooter';
import { TodoNotification } from './components/TodoNotification';
import { TodoContext } from './context/TodoContext';
import { getTodos } from './api/todos';
import { ErrorContext } from './context/ErrorContext';
import { USER_ID } from './utils/variables';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const { todos, setTodos } = useContext(TodoContext);
const { setErrorMessage } = useContext(ErrorContext);

Choose a reason for hiding this comment

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

Create hooks for contexts so you don't need to pass context every time, for example:

const useTodo = () => useContext(TodoContext);


const [isActive, setIsActive] = useState(false);

useEffect(() => {
getTodos(USER_ID)
.then(setTodos)
.catch(() => {
setErrorMessage('Unable to load 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">
<TodoHeader onHandleActive={(value) => setIsActive(value)} />

Choose a reason for hiding this comment

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

Suggested change
<TodoHeader onHandleActive={(value) => setIsActive(value)} />
<TodoHeader onHandleActive={setIsActive} />


<TodoList
isActive={isActive}
onHandleActive={(value) => setIsActive(value)}

Choose a reason for hiding this comment

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

Suggested change
onHandleActive={(value) => setIsActive(value)}
onHandleActive={setIsActive}

/>

{Boolean(todos.length) && (
<TodoFooter />
)}
</div>

<TodoNotification />
</div>
);
};
22 changes: 0 additions & 22 deletions src/UserWarning.tsx

This file was deleted.

20 changes: 20 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

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

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

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

export const updateTodo = (todoId: number, todo: Partial<Todo>) => {
return client.patch<Todo>(`/todos/${todoId}`, todo);
};
112 changes: 112 additions & 0 deletions src/components/TodoEditItem/TodoEditItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import {
useContext, useEffect, useRef, useState,
} from 'react';
import classnames from 'classnames';
import { Todo } from '../../types/Todo';
import { TodoContext } from '../../context/TodoContext';
import { ErrorContext } from '../../context/ErrorContext';
import { updateTodo } from '../../api/todos';

type Props = {
todo: Todo;
onEditedId: () => void;
onDelete: (value: Todo) => void;
isLoading: boolean;
onLoad: (value: boolean) => void;
};

export const TodoEditItem: React.FC<Props> = ({
todo, onEditedId, onDelete, isLoading, onLoad,
}) => {
const { id, completed } = todo;
const { todos, setTodos } = useContext(TodoContext);
const { setErrorMessage } = useContext(ErrorContext);

const editInputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
editInputRef.current?.focus();
}, []);

const [newTitle, setNewTitle] = useState(todo.title);

const updateNewTodo = () => {
if (!newTitle.trim()) {
onDelete(todo);

return;
}

const todosCopy = [...todos];
const index = todos.findIndex(({ id: currentId }) => currentId === id);
const updatedTodo = {
...todosCopy[index],
title: newTitle,
};

todosCopy.splice(index, 1, updatedTodo);

Choose a reason for hiding this comment

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

Don't use splice and findIndex, just use map instead


onLoad(true);

updateTodo(todo.id, updatedTodo)
.then(() => setTodos(todosCopy))
.catch(() => setErrorMessage('Unable to update a todo'))
.finally(() => {
onLoad(false);
onEditedId();
});
};

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

updateNewTodo();
};

const handlePressEscape = (
event: React.KeyboardEvent<HTMLInputElement>,
) => {
if (event.key === 'Escape') {
onEditedId();
}
};

return (
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
checked={completed}
/>
</label>

<form onSubmit={handleEditTodo}>
<input
ref={editInputRef}
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value={newTitle}
onChange={(event) => setNewTitle(event.target.value)}
onBlur={updateNewTodo}
onKeyUp={handlePressEscape}
/>
</form>

<div
data-cy="TodoLoader"
className={classnames(
'modal overlay', {
'is-active': isLoading,
},
)}
>
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
);
};
1 change: 1 addition & 0 deletions src/components/TodoEditItem/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoEditItem';
91 changes: 91 additions & 0 deletions src/components/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { useContext, useMemo } from 'react';
import classnames from 'classnames';
import { Status } from '../../types/Status';
import { FilterContext } from '../../context/FilterContext';
import { TodoContext } from '../../context/TodoContext';
import { deleteTodo } from '../../api/todos';
import { ErrorContext } from '../../context/ErrorContext';

export const TodoFooter = () => {
const { todos, setTodos } = useContext(TodoContext);
const { selectedFilter, setSelectedFilter } = useContext(FilterContext);

Choose a reason for hiding this comment

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

You created hooks for contexts, but not for this one) Let's create for the FilterContext too

const { setErrorMessage } = useContext(ErrorContext);

const hasCompletedTodo = useMemo(() => {
return todos.some(todo => todo.completed);
}, [todos]);

const clearCompleted = () => {
todos.forEach(({ id, completed }) => {
if (completed) {
deleteTodo(id)
.then(() => {
setTodos(prevState => prevState.filter(todo => todo.id !== id));
})
.catch(() => setErrorMessage('Unable to delete a todo'));
}
});

Choose a reason for hiding this comment

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

Don't use forEach for async operations, use for of with async/await or collect requests with mapand thenPromise.all`.

Also, add loaders to notify users what todos will be deleted.

};

return (
<footer data-cy="Footer" className="todoapp__footer">
<span className="todo-count" data-cy="TodosCounter">
{`${todos.filter(({ completed }) => !completed).length} items left`}
</span>

<nav data-cy="Filter" className="filter">
<a
data-cy="FilterLinkAll"
href="#/"
className={classnames(
'filter__link',
{
selected: selectedFilter === Status.All,
},
)}
onClick={() => setSelectedFilter(Status.All)}
>
All
</a>

<a
data-cy="FilterLinkActive"
href="#/active"
className={classnames(
'filter__link',
{
selected: selectedFilter === Status.Active,
},
)}
onClick={() => setSelectedFilter(Status.Active)}
>
Active
</a>

<a
data-cy="FilterLinkCompleted"
href="#/completed"
className={classnames(
'filter__link',
{
selected: selectedFilter === Status.Completed,
},
)}
onClick={() => setSelectedFilter(Status.Completed)}
>
Completed
</a>
</nav>

<button
data-cy="ClearCompletedButton"
type="button"
className="todoapp__clear-completed"
disabled={!hasCompletedTodo}
onClick={clearCompleted}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/components/TodoFooter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoFooter';
Loading