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

Solution #1596

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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://anna-daryna.github.io/react_todo-app-with-api/) and add it to the PR description.
2 changes: 1 addition & 1 deletion cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { defineConfig } = require('cypress');

module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
baseUrl: 'http://localhost:5173',
specPattern: 'cypress/integration/**/*.spec.{js,ts,jsx,tsx}',
},
video: true,
Expand Down
8 changes: 4 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": "^1.9.12",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
291 changes: 276 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,287 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState, useRef } from 'react';
import classNames from 'classnames';

import { UserWarning } from './UserWarning';
import { getTodos, USER_ID } from './api/todos';
import { Todo } from './types/Todo';
import * as Methods from './api/todos';
import Header from './components/Header';
import TodoList from './components/TodoList';
import Footer from './components/Footer';

const USER_ID = 0;
export enum TodoStatus {
All = 'All',
Active = 'Active',
Completed = 'Completed',
}

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [statusFilter, setStatusFilter] = useState<TodoStatus>(TodoStatus.All);
const [newTodo, setNewTodo] = useState<string>('');
const [isInputDisabled, setIsInputDisabled] = useState(false);
const [loadingTodoId, setLoadingTodoId] = useState<number | null>(null);
const [pendingTodos, setPendingTodos] = useState<Todo[]>([]);

const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
const loadTodos = async () => {
try {
const fetchedTodos = await getTodos();

setTodos(fetchedTodos);
} catch {
setErrorMessage('Unable to load todos');
}
};

loadTodos();
}, []);

useEffect(() => {
if (errorMessage) {
const timer = setTimeout(() => {
setErrorMessage(null);
}, 3000);

return () => clearTimeout(timer);
}

return undefined;
}, [errorMessage]);

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

const filteredTodos = todos.filter(todo => {
switch (statusFilter) {
case TodoStatus.Active:
return !todo.completed;
case TodoStatus.Completed:
return todo.completed;
default:
return true;
}
});

const activeCount = todos.reduce(
(count, todo) => (!todo.completed && todo.id > 0 ? count + 1 : count),
0,
);

const addTodo = async (event: React.FormEvent) => {
event.preventDefault();

if (newTodo.trim() === '') {
setErrorMessage('Title should not be empty');

return;
}

const trimmedTitle = newTodo.trim();
const tempId = Math.random();
const tempTodoToAdd: Todo = {
id: tempId,
title: trimmedTitle,
completed: false,
userId: USER_ID,
};

setPendingTodos([...pendingTodos, tempTodoToAdd]);
setLoadingTodoId(tempId);
setIsInputDisabled(true);

try {
const addedTodo = await Methods.addTodo({
title: trimmedTitle,
completed: false,
userId: USER_ID,
});

setTodos(currentTodos => [...currentTodos, addedTodo]);
setPendingTodos(currentPendingTodos =>
currentPendingTodos.filter(todo => todo.id !== tempId),
);
setNewTodo('');
} catch {
setErrorMessage('Unable to add a todo');
setPendingTodos(currentPendingTodos =>
currentPendingTodos.filter(todo => todo.id !== tempId),
);
} finally {
setLoadingTodoId(null);
setIsInputDisabled(false);
inputRef?.current?.focus();
}
};

const toggleTodoStatus = async (todoId: number, completed: boolean) => {
setLoadingTodoId(todoId);

try {
await Methods.updateTodo(todoId, { completed });

setTodos(currentTodos =>
currentTodos.map(todo =>
todo.id === todoId ? { ...todo, completed } : todo,
),
);
} catch {
setErrorMessage('Unable to update a todo');
} finally {
setLoadingTodoId(null);
inputRef?.current?.focus();
}
};

const toggleAllTodos = async () => {
const areAllCompleted = todos.every(todo => todo.completed);
const newCompletedStatus = !areAllCompleted;

const todosToUpdate = todos.filter(
todo => todo.completed !== newCompletedStatus,
);

try {
await Promise.all(
todosToUpdate.map(async todo => {
await Methods.updateTodo(todo.id, { completed: newCompletedStatus });
}),
);

setTodos(currentTodos =>
currentTodos.map(todo => ({
...todo,
completed: newCompletedStatus,
})),
);
} catch {
setErrorMessage('Unable to update all todos');
}
};

const deleteTodo = async (todoId: number) => {
setLoadingTodoId(todoId);

try {
await Methods.deleteTodo(todoId);

setTodos(currentTodos => currentTodos.filter(todo => todo.id !== todoId));
} catch {
setErrorMessage('Unable to delete a todo');
} finally {
setLoadingTodoId(null);
inputRef?.current?.focus();
}
};

const clearCompletedTodos = async () => {
const completedTodos = todos.filter(todo => todo.completed);
let errorOccurred = false;

try {
await Promise.all(
completedTodos.map(async todo => {
try {
await Methods.deleteTodo(todo.id);

setTodos(currentTodos =>
currentTodos.filter(currentTodo => currentTodo.id !== todo.id),
);
} catch {
setErrorMessage('Unable to delete a todo');
errorOccurred = true;
}
}),
);
} catch {
setErrorMessage('Error occurred while clearing completed todos.');
} finally {
if (!errorOccurred) {
setErrorMessage(null);
}

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

const updateTodo = async (todoId: number, newTitle: string) => {
setLoadingTodoId(todoId);

setTodos(currentTodos =>
currentTodos.map(todo =>
todo.id === todoId ? { ...todo, title: newTitle } : todo,
),
);

setLoadingTodoId(null);
};

const hideError = () => setErrorMessage(null);

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
newTitle={newTodo}
setNewTitle={setNewTodo}
onSubmit={addTodo}
isInputDisabled={isInputDisabled}
inputRef={inputRef}
toggleAllTodos={toggleAllTodos}
areAllCompleted={todos.every(todo => todo.completed)}
todos={todos}
/>

<TodoList
filteredTodos={[...filteredTodos, ...pendingTodos]}
loadingTodoId={loadingTodoId}
deleteTodo={deleteTodo}
toggleTodoStatus={toggleTodoStatus}
setErrorMessage={setErrorMessage}
updateTodo={updateTodo}
/>

{todos.length > 0 && (
<Footer
statusFilter={statusFilter}
setStatusFilter={setStatusFilter}
filteredTodos={filteredTodos}
activeCount={activeCount}
clearCompletedTodos={clearCompletedTodos}
/>
)}
</div>

<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={hideError}
/>
{errorMessage}
</div>
</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 = 1870;

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

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

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

export const updateTodo = (todoId: number, updatedData: Partial<Todo>) => {
return client.patch<Todo>(`/todos/${todoId}`, updatedData);
};
Loading
Loading