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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,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://Dima2702.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
295 changes: 281 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,293 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import cn from 'classnames';
import { UserWarning } from './UserWarning';
import {
getTodoError,
todosService,
TodosServiceError,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { TodoItem } from './components/TodoItem';
import { ErrorNotification } from './components/ErrorNotification';
import { useErrorMessage } from './hooks/useErrorMessage';
import { StatusFilter, TodoStatus } from './components/StatusFilter';
import { getSortedTodos } from './utils/getSortedTodos';
import { AddTodoForm, AddTodoFormData } from './components/AddTodoForm';
import { TodoCreate } from './types/TodoCreate';
import { TodoUpdate } from './types/TodoUpdate';

const USER_ID = 0;
function getFilteredTodos(todos: Todo[], { status }: { status: TodoStatus }) {
let filteredTodos = todos;

if (status !== TodoStatus.All) {
filteredTodos = filteredTodos.filter(todo => {
switch (status) {
case TodoStatus.Completed:
return todo.completed;

case TodoStatus.Active:
return !todo.completed;

default:
throw new Error('Massing case in getFilteredTodos status filter');
}
});
}

return filteredTodos;
}

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [statusFilter, setStatusFilter] = useState(TodoStatus.All);
const newTodoTitleRef = useRef<HTMLInputElement>(null);

const { errorMessage, resetErrorMessage, setErrorMessage } =
useErrorMessage();

const { completed: completedTodos, active: activeTodos } =
getSortedTodos(todos);

const handleAddToLoading = useCallback((todoId: number) => {
setLoadingTodoIds(current => [...current, todoId]);
}, []);

const handleRemoveFromLoading = useCallback((todoId: number) => {
setLoadingTodoIds(current => current.filter(id => id !== todoId));
}, []);

const handleDeleteTodo = useCallback(
(todoId: number) => {
handleAddToLoading(todoId);

todosService
.delete(todoId)
.then(() => {
setTodos(current => current.filter(todo => todo.id !== todoId));
})
.catch(() => {
setErrorMessage(getTodoError(TodosServiceError.UnableToDeleteTodo));
})
.finally(() => {
handleRemoveFromLoading(todoId);

newTodoTitleRef.current?.focus();
});
},
[
newTodoTitleRef,
handleAddToLoading,
handleRemoveFromLoading,
setErrorMessage,
],
);

const handleClearCompleted = useCallback(() => {
completedTodos.forEach(todo => {
handleDeleteTodo(todo.id);
});
}, [completedTodos, handleDeleteTodo]);

const handleCreateTodo = useCallback(
(
values: AddTodoFormData,
{
onSuccess,
onError,
}: {
onSuccess?: (createdTodo: Todo) => void;
onError?: () => void;
} = {},
) => {
if (newTodoTitleRef.current) {
newTodoTitleRef.current.disabled = true;
}

const createTodoDto: TodoCreate = {
title: values.title,
userId: USER_ID,
completed: false,
};

setTempTodo({
id: 0,
...createTodoDto,
});

todosService
.create(createTodoDto)
.then(createdTodo => {
onSuccess?.(createdTodo);
setTodos(current => [...current, createdTodo]);
})
.catch(() => {
setErrorMessage(getTodoError(TodosServiceError.UnableToAddTodo));

onError?.();
})
.finally(() => {
setTempTodo(null);
if (newTodoTitleRef.current) {
newTodoTitleRef.current.disabled = false;
}

newTodoTitleRef.current?.focus();
});
},
[newTodoTitleRef, setErrorMessage],
);

const handleUpdateTodo = useCallback(
(
todoId: number,
data: TodoUpdate,
{
onSuccess,
onError,
}: { onSuccess?: (updatedTodo: Todo) => void; onError?: () => void } = {},
) => {
handleAddToLoading(todoId);
todosService
.update(todoId, data)
.then(updatedTodo => {
setTodos(current =>
current.map(todo => {
return todo.id === updatedTodo.id ? updatedTodo : todo;
}),
);

onSuccess?.(updatedTodo);
})
.catch(() => {
setErrorMessage(getTodoError(TodosServiceError.UnableToUpdateTodo));

onError?.();
})
.finally(() => {
handleRemoveFromLoading(todoId);
});
},
[handleAddToLoading, handleRemoveFromLoading, setErrorMessage],
);

const handleBulkToggleStatus = useCallback(() => {
if (activeTodos.length !== 0) {
activeTodos.forEach(({ id, ...todo }) => {
handleUpdateTodo(id, {
title: todo.title,
userId: todo.userId,
completed: !todo.completed,
});
});

return;
}

todos.forEach(({ id, ...todo }) => {
handleUpdateTodo(id, {
title: todo.title,
userId: todo.userId,
completed: !todo.completed,
});
});
}, [todos, activeTodos, handleUpdateTodo]);

useEffect(() => {
todosService
.list()
.then(todosFromServer => setTodos(todosFromServer))
.catch(() => {
setErrorMessage(getTodoError(TodosServiceError.UnableToLoadTodos));
})
.finally();
}, [setErrorMessage]);

const filteredTodos = getFilteredTodos(todos, { status: statusFilter });

const showTodosAndFooter = todos.length > 0;
const showToggleButton = todos.length > 0;
const showClearCompletedButton = completedTodos.length > 0;
const activeTodosAmount = activeTodos.length;
const shouldToggleButtonBeActive = completedTodos.length === todos.length;

if (!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">
<header className="todoapp__header">
{/* this button should have `active` class only if all todos are completed */}
{showToggleButton && (
<button
type="button"
className={cn('todoapp__toggle-all', {
active: shouldToggleButtonBeActive,
})}
data-cy="ToggleAllButton"
onClick={handleBulkToggleStatus}
/>
)}

<AddTodoForm
ref={newTodoTitleRef}
onError={setErrorMessage}
onSubmit={handleCreateTodo}
/>
</header>
{showTodosAndFooter && (
<>
<section className="todoapp__main" data-cy="TodoList">
{filteredTodos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onDelete={handleDeleteTodo}
loading={loadingTodoIds.includes(todo.id)}
onUpdate={handleUpdateTodo}
/>
))}

{tempTodo && <TodoItem todo={tempTodo} loading />}
</section>

{/* Hide the footer if there are no todos */}
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodosAmount} items left
</span>

<StatusFilter
value={statusFilter}
onValueChange={setStatusFilter}
/>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!showClearCompletedButton}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
</>
)}
</div>
{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}
<ErrorNotification
notification={errorMessage}
onClear={resetErrorMessage}
/>
</div>
);
};
34 changes: 34 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Todo } from '../types/Todo';
import { TodoCreate } from '../types/TodoCreate';
import { TodoUpdate } from '../types/TodoUpdate';
import { client } from '../utils/fetchClient';

export const USER_ID = 4252;

export const todosService = {
list: () => client.get<Todo[]>(`/todos?userId=${USER_ID}`),
create: (data: TodoCreate) => client.post<Todo>('/todos', data),
delete: (todoId: number) => client.delete(`/todos/${todoId}`),
update: (todoId: number, data: TodoUpdate) =>
client.patch<Todo>(`/todos/${todoId}`, data),
};

export enum TodosServiceError {
UnableToLoadTodos = 'todos_service_unable_to_load_todos',
TitleShouldNotBeEmpty = 'todos_service_title_should_not_be_empty',
UnableToDeleteTodo = 'todos_service_unable_to_delete_todo',
UnableToAddTodo = 'todos_service_unable_to_add_todo',
UnableToUpdateTodo = 'todos_service_unable_to_update_todo',
}

const TODOS_ERROR_MESSAGES: Record<TodosServiceError, string> = {
[TodosServiceError.UnableToLoadTodos]: 'Unable to load todos',
[TodosServiceError.TitleShouldNotBeEmpty]: 'Title should not be empty',
[TodosServiceError.UnableToDeleteTodo]: 'Unable to delete a todo',
[TodosServiceError.UnableToAddTodo]: 'Unable to add a todo',
[TodosServiceError.UnableToUpdateTodo]: 'Unable to update a todo',
};

export function getTodoError(errorKey: TodosServiceError): string {
return TODOS_ERROR_MESSAGES[errorKey];
}
Loading
Loading