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 5 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, { 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 { useTodo } from './context/TodoContext';
import { getTodos } from './api/todos';
import { useError } from './context/ErrorContext';
import { USER_ID } from './utils/variables';

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

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

<TodoList
isActive={isActive}
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);
};
128 changes: 128 additions & 0 deletions src/components/TodoEditItem/TodoEditItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import {
useEffect, useRef, useState,
} from 'react';
import classnames from 'classnames';
import { Todo } from '../../types/Todo';
import { useTodo } from '../../context/TodoContext';
import { useError } from '../../context/ErrorContext';
import { updateTodo } from '../../api/todos';
// import { useTitle } from '../../context/TitleContext';

Choose a reason for hiding this comment

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

Remove comments


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 } = useTodo();
const { setErrorMessage } = useError();

const editInputRef = useRef<HTMLInputElement>(null);

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

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

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

return;
}

const updatedTodos = todos.map((currentTodo) => {
if (currentTodo.id === id) {
return {
...currentTodo,
title: newTitle,
};
}

return currentTodo;
});

const updatedTodo = updatedTodos.find(({ id: updatedId }) => {
return updatedId === id;
});

onLoad(true);

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

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

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

if (todo.title === newTitle) {
onEditedId();

return;
}

updateNewTodo();
};

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';
98 changes: 98 additions & 0 deletions src/components/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { useContext, useMemo } from 'react';
import classnames from 'classnames';
import { Status } from '../../types/Status';
import { FilterContext } from '../../context/FilterContext';
import { useTodo } from '../../context/TodoContext';
import { deleteTodo } from '../../api/todos';
import { useError } from '../../context/ErrorContext';

export const TodoFooter = () => {
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 { todos, setTodos } = useTodo();
const { setErrorMessage } = useError();

const isActiveItemsLeft = todos
.filter(({ completed }) => !completed).length;

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

const clearCompleted = () => {
const deletePromises = todos
.filter((todo) => todo.completed)
.map(({ id }) => deleteTodo(id));

Promise.all(deletePromises)
.then(() => {
setTodos((prevState) => prevState.filter((todo) => !todo.completed));
})
.catch(() => {
setErrorMessage('Unable to delete a todo');
});
};

return (
<footer data-cy="Footer" className="todoapp__footer">
<span className="todo-count" data-cy="TodosCounter">
{isActiveItemsLeft > 1
? `${isActiveItemsLeft} items left`
: '1 item 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
Loading