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

Develop #1535

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Develop #1535

Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and implement the ability to toggle and rename todos.
## Toggling a todo status

Toggle the `completed` status on `TodoStatus` change:

- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save.
- covered the todo with a loader overlay while waiting for API response;
- the status should be changed on success;
Expand Down Expand Up @@ -38,6 +39,7 @@ Implement the ability to edit a todo title on double click:
- or the deletion error message if we tried to delete the todo.

## If you want to enable tests

- open `cypress/integration/page.spec.js`
- replace `describe.skip` with `describe` for the root `describe`

Expand All @@ -47,4 +49,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://OkMoroz.github.io/react_todo-app-with-api/) and add it to the PR description.
190 changes: 171 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,178 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';
import React, { useState, useEffect } from 'react';
import { addTodo, deleteTodo, getTodos, updateTodo } from './api/todos';
// import { todos } from './api/todos';

const USER_ID = 0;
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { Errors } from './components/Errors';

import { loadingObject } from './utils/loadingObject';
import { filteredTodos } from './utils/filteredTodos';

import { Todo } from './types/Todo';
import { ErrorMessage } from './types/Errors';
import { Loading } from './types/Loading';
import { Filters } from './types/Filters';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<string>('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);

Choose a reason for hiding this comment

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

в тебе є enum по помилкам, типізуй useState типом Error
щоб не робити тут додаткової перевірки на пустий рядок, то можеж в enum прописати, наприклад Nothing: '', aбо Empty: ''

Бо в даному випадку в цей state можна покласти довільний рядок

Copy link
Author

Choose a reason for hiding this comment

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

Дякую, візьму до уваги

const [filter, setFilter] = useState<Filters>(Filters.All);
const [loadingId, setLoadingId] = useState<Loading>({});

Choose a reason for hiding this comment

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

краще зберігати саму id, без об'єкта і судячи з назви там має бути id

useEffect(() => {
const timeoutId = setTimeout(() => setErrorMessage(''), 3000);

getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage(ErrorMessage.UnableToLoad);
clearTimeout(timeoutId);
});

return () => clearTimeout(timeoutId);
}, []);

const handleAdd = (newTodo: Todo): Promise<Todo | void> => {
setTempTodo(newTodo);

Choose a reason for hiding this comment

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

why u need Todo in this place?
you don't use this feature to get an item(onSubmit - ur logic)

Suggested change
const handleAdd = (newTodo: Todo): Promise<Todo | void> => {
const handleAdd = (newTodo: Todo): Promise<void> => {


return addTodo(newTodo).then(newTodoRes => {
setTodos(currentTodos => [...currentTodos, newTodoRes]);
});
};

const updateCompleted = (
updatedTodo: Todo,
key: keyof Todo,
value: boolean | string,
) => {
return updateTodo({ ...updatedTodo, [key]: value })
.then((updatedTodoFromServer: Todo) => {
setTodos(currentTodos => {
return currentTodos.map(todo =>
todo.id === updatedTodo.id ? updatedTodoFromServer : todo,
);
});

return false;
})
.catch(() => {
setErrorMessage(ErrorMessage.UnableToUpdate);

return true;
});
};

const handleToggleAll = () => {
const activeTodos = todos.filter(todo => !todo.completed);
const activeTodosIds = loadingObject(activeTodos);

if (activeTodos.length) {
setLoadingId(activeTodosIds);

Promise.all(
activeTodos.map(todo => updateTodo({ ...todo, completed: true })),
)
.then(() =>
setTodos(currentTodos => {
return currentTodos.map(todo => {
if (Object.hasOwn(activeTodosIds, todo.id)) {
return { ...todo, completed: true };
} else {
return todo;
}
});
}),
)
.catch(() => setErrorMessage(ErrorMessage.UnableToUpdate))
.finally(() => setLoadingId({}));

return;
}

setLoadingId(loadingObject(todos));
Promise.all(todos.map(todo => updateTodo({ ...todo, completed: false })))
.then(() =>
setTodos(prevTodos => {
return prevTodos.map(todo => ({ ...todo, completed: false }));
}),
)
.catch(() => setErrorMessage(ErrorMessage.UnableToUpdate))
.finally(() => setLoadingId({}));
};

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

setLoadingId(loadingObject(completedTodos));

Promise.allSettled(
completedTodos.map(todo => deleteTodo(todo.id).then(() => todo)),
)
.then(values => {
values.map(val => {
if (val.status === 'rejected') {
setErrorMessage(ErrorMessage.UnableToDelete);
} else {
setTodos(currentTodos => {
const todoId = val.value as Todo;

return currentTodos.filter(todo => todo.id !== todoId.id);
});
}
});
})
.finally(() => setLoadingId({}));
};

const handleDelete = (todoId: number): Promise<void> => {
return deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage(ErrorMessage.UnableToDelete);
})
.finally(() => setTempTodo(null));
};

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
tempTodo={tempTodo}
todos={todos}
onToggleAll={handleToggleAll}
onChangeTempTodo={setTempTodo}
setErrorMessage={setErrorMessage}
onSubmit={handleAdd}
/>

<TodoList
todos={filteredTodos(todos, filter)}
tempTodo={tempTodo}
loadingId={loadingId}
onEdit={updateCompleted}
onDelete={handleDelete}
/>

{todos.length > 0 && (
<Footer

Choose a reason for hiding this comment

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

краще вказати перевірку !!todos.length

Copy link
Author

Choose a reason for hiding this comment

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

чому саме той варіант кращий?

Choose a reason for hiding this comment

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

@OkMoroz !! - converts the value to boolean type and more readable i think

todos={todos}
selectedFilter={filter}
onFilteredStatus={setFilter}
onDeleteCompleted={handleDeleteCompleted}
/>
)}
</div>

<Errors message={errorMessage} clearError={() => setErrorMessage('')} />
</div>
);
};
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 USER_ID = 2132;

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

export const addTodo = (data: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', data);
};

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

export const updateTodo = ({ id, ...todo }: Todo) => {
return client.patch<Todo>(`/todos/${id}`, todo);
};
39 changes: 39 additions & 0 deletions src/components/Errors.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React, { useEffect } from 'react';
import cn from 'classnames';

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

export const Errors: React.FC<Props> = props => {
const { message, clearError } = props;

useEffect(() => {
const timeOut = setTimeout(clearError, 3000);

return () => {
clearTimeout(timeOut);
};
}, [message]);

Check warning on line 18 in src/components/Errors.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

React Hook useEffect has a missing dependency: 'clearError'. Either include it or remove the dependency array

return (
<div
data-cy="ErrorNotification"
className={cn(
'notification',
'is-danger',
'is-light has-text-weight-normal',
{ hidden: !message },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={clearError}
/>
{message}
</div>
);
};
59 changes: 59 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react';
import cn from 'classnames';
import { Filters } from '../types/Filters';
import { Todo } from '../types/Todo';

type Props = {
todos: Todo[];
selectedFilter: Filters;
onFilteredStatus: (filter: Filters) => void;
onDeleteCompleted: () => void;
};

export const Footer: React.FC<Props> = props => {
const { todos, selectedFilter, onFilteredStatus, onDeleteCompleted } = props;

const filtersValue = Object.values(Filters);
const activeTodosCount = todos.filter(todo => !todo.completed).length;
const isCompleted = todos.some(todo => todo.completed);

Choose a reason for hiding this comment

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

useMemo?

let isDeleteCompleted = false;

Choose a reason for hiding this comment

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

loading state?


const handleDeleteCompleted = () => {
isDeleteCompleted = true;
onDeleteCompleted();
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodosCount} items left
</span>
<nav className="filter" data-cy="Filter">
{filtersValue.map(filter => (
<a
key={filter}
href={`#/${filter !== Filters.All ? filter.toLowerCase() : ''}`}

Choose a reason for hiding this comment

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

will it be better?

Suggested change
href={`#/${filter !== Filters.All ? filter.toLowerCase() : ''}`}
href={`#/${filter !== Filters.All && filter.toLowerCase()}`}

className={cn('filter__link', {
selected: filter === selectedFilter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => onFilteredStatus(filter)}
>
{filter}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={isDeleteCompleted || !isCompleted}
style={{ visibility: !isCompleted ? 'hidden' : 'visible' }}
onClick={handleDeleteCompleted}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading