Skip to content
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
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://naviailpach.github.io/react_todo-app-with-api/) and add it to the PR description.
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"devDependencies": {
"@cypress/react18": "^2.0.1",
"@mate-academy/scripts": "^1.8.5",
"@mate-academy/scripts": "^2.1.3",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
248 changes: 231 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,240 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import * as todoService from './api/todos';
import { Filter } from './utils/Filter';
import { Todo } from './types/todo';
import { ErrorMessage } from './utils/ErrorMessage';
import { ErrorNotification } from './components/ErrorNotification';
import { TodoFooter } from './components/TodoFooter';
import { TodoList } from './components/TodoList';
import { TodoHeader } from './components/TodoHeader';

export const App: React.FC = () => {
if (!USER_ID) {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState(ErrorMessage.Empty);
const [filter, setFilter] = useState<Filter>(Filter.All);
const [query, setQuery] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);

const [isLoading, setIsLoading] = useState(false);
const [loadingIds, setLoadingIds] = useState<number[]>([]);

useEffect(() => {
todoService
.getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage(ErrorMessage.Load);
});
}, []);

useEffect(() => {
if (!errorMessage) {
return;
}

const timer = setTimeout(() => {
setErrorMessage(ErrorMessage.Empty);
}, 3000);

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

const filteredTodos = todos.filter(todo => {
switch (filter) {
case 'active':
return !todo.completed;

case 'completed':
return todo.completed;

default:
return true;
}
});

const addTodo = ({ title, completed, userId }: Omit<Todo, 'id'>) => {
setTempTodo({ id: 0, title, completed, userId });
setIsLoading(true);

todoService
.createTodo({ title, completed, userId })
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setQuery('');
})
.catch(() => {
setErrorMessage(ErrorMessage.Add);
})
.finally(() => {
setTempTodo(null);
setIsLoading(false);
});
};

const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
if (!isLoading) {
inputRef.current?.focus();
}
}, [isLoading]);

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

if (!query.trim()) {
setErrorMessage(ErrorMessage.TitleEmpty);

return;
}

addTodo({
title: query.trim(),
completed: false,
userId: todoService.USER_ID,
});
};

const deleteTodo = (todoId: number, onSuccess?: () => void) => {
setLoadingIds(current => [...current, todoId]);

todoService
.deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);

onSuccess?.();
})
.catch(() => {
setErrorMessage(ErrorMessage.Delete);
})
.finally(() => {
setLoadingIds(current => current.filter(id => id !== todoId));
if (!onSuccess) {
inputRef.current?.focus();
}
});
};

const handleFilterChange = (
event: React.MouseEvent<HTMLAnchorElement>,
value: Filter,
) => {
event.preventDefault();
setFilter(value);
};

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

setLoadingIds(current => [
...current,
...completedTodos.map(todo => todo.id),
]);

Promise.allSettled(
completedTodos.map(todo => todoService.deleteTodo(todo.id)),
).then(results => {
const failedInds = results.some(result => result.status === 'rejected');

if (failedInds) {
setErrorMessage(ErrorMessage.Delete);
}

const successfulIds = results
.map((result, index) =>
result.status === 'fulfilled' ? completedTodos[index].id : -1,
)
.filter(id => id !== -1);

setTodos(current =>
current.filter(todo => !successfulIds.includes(todo.id)),
);

inputRef.current?.focus();
});
};

const updateTodo = (updatedTodo: Todo, onSuccess?: () => void) => {
setLoadingIds(current => [...current, updatedTodo.id]);

todoService
.updateTodo(updatedTodo)
.then(todo => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(t => t.id === updatedTodo.id);

newTodos.splice(index, 1, todo);

return newTodos;
});

onSuccess?.();
})
.catch(() => {
setErrorMessage(ErrorMessage.Update);
})
.finally(() => {
setLoadingIds(current => current.filter(id => id !== updatedTodo.id));
});
};

const toggleAll = () => {
const allCompleted = todos.every(todo => todo.completed);
const todosToToggle = todos.filter(todo => todo.completed === allCompleted);

todosToToggle.forEach(todo => {
updateTodo({ ...todo, completed: !allCompleted });
});
};

if (!todoService.USER_ID) {
return <UserWarning />;
}

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
todos={todos}
query={query}
inputRef={inputRef}
isLoading={isLoading}
onQueryChange={setQuery}
onSubmit={handleSubmit}
toggleAll={toggleAll}
/>

{todos.length > 0 && (
<TodoList
todos={filteredTodos}
tempTodo={tempTodo}
loadingIds={loadingIds}
onDelete={deleteTodo}
updateTodo={updateTodo}
/>
)}

{todos.length > 0 && (
<TodoFooter
todos={todos}
filter={filter}
onFilterChange={handleFilterChange}
clearCompleted={clearCompleted}
/>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
onClose={() => setErrorMessage(ErrorMessage.Empty)}
/>
</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 = 4193;

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

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

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

export const updateTodo = ({ id, title, completed, userId }: Todo) => {
return client.patch<Todo>(`/todos/${id}`, { title, completed, userId });
};
31 changes: 31 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import classNames from 'classnames';

import React from 'react';

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

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
onClose,
}) => (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{
hidden: !errorMessage,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>
{errorMessage}
</div>
);
1 change: 1 addition & 0 deletions src/components/ErrorNotification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { ErrorNotification } from './ErrorNotification';
Loading
Loading