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

Dev (Later will add animation from previous task, i hope) #1504

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
6 changes: 4 additions & 2 deletions 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 All @@ -30,14 +31,15 @@ Implement the ability to edit a todo title on double click:
- saves changes on the form submit (just press `Enter`);
- save changes when the field loses focus (`onBlur`);
- if the new title is the same as the old one just cancel editing;
- cancel editing on `Esс` key `keyup` event;
- cancel editing on `Esc` key `keyup` event;
- if the new title is empty delete the todo the same way the `x` button does it;
- if the title was changed show the loader while waiting for the API response;
- update the todo title on success;
- show `Unable to update a todo` in case of API error;
- 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://MaxF1996.github.io/react_todo-app-with-api/) and add it to the PR description.
12 changes: 7 additions & 5 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
315 changes: 299 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,309 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
getTodos,
addTodo,
deleteTodo,
updateTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { Filters } from './types/Filters';
import { Errors } from './types/Errors';
import { UpdateReasons } from './types/UpdateReasons';
import { useDelayedSetState } from './hooks/useDelayedSetState';
import { Header } from './blocks/Header';
import { Footer } from './blocks/Footer';
import { TodoList } from './components/TodoList';
import { ErrorNotification } from './components/ErrorNotification';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [filteredTodos, setFilteredTodos] = useState<Todo[]>([]);
const [currentError, setCurrentError] = useState<Errors | null>(null);
const [currentFilter, setCurrentFilter] = useState<Filters>(Filters.all);
const [title, setTitle] = useState<string>('');
const [isNewTodoAdding, setIsNewTodoAdding] = useState<boolean>(false);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [isAdded, setIsAdded] = useState<boolean | null>(false);
const [todoIdsForRemoving, setTodoIdsForRemoving] = useState<number[] | null>(
null,
);
const [isTodoDeleting, setIsTodoDeleting] = useState<boolean>(false);
const [reasonForUpdate, setReasonForUpdate] = useState<UpdateReasons | null>(
null,
);
const [typeOfStatusChange, setTypeOfStatusChange] = useState<boolean | null>(
null,
);
const [titleForUpdate, setTitleForUpdate] = useState<string>('');
const [titleSuccess, setTitleSuccess] = useState<boolean | null>(false);
const [idsForUpdate, setIdsForUpdate] = useState<number[] | []>([]);
const [needAutoFocus, setNeedAutoFocus] = useState<boolean | null>(false);

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => {
setCurrentError(Errors.load);
});
}, []);

useEffect(() => {
setFilteredTodos(todos);
}, [todos]);

useDelayedSetState(currentError, setCurrentError);
useDelayedSetState(isAdded, setIsAdded, false, 1000);
useDelayedSetState(titleSuccess, setTitleSuccess, false, 1000);

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

const newTodo = { id: 0, userId: USER_ID, title, completed: false };

setIsNewTodoAdding(true);
setTempTodo(newTodo);

addTodo(title)
.then((todo: Todo) => {
setTodos([...todos, todo]);
setIsAdded(true);
})
.catch(() => {
setCurrentError(Errors.add);
setNeedAutoFocus(true);
})
.finally(() => {
setIsNewTodoAdding(false);
setTempTodo(null);
});

setTitle('');
setIsAdded(false);
}, [title]);

Check warning on line 86 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

React Hook useEffect has a missing dependency: 'todos'. Either include it or remove the dependency array. You can also do a functional update 'setTodos(t => ...)' if you only need 'todos' in the 'setTodos' call

const handleFilteredTodos = (filter: Filters) => {
const { all, active, completed } = Filters;

switch (filter) {
case all:
setFilteredTodos(todos);
break;
case active:
setFilteredTodos(todos.filter(todo => !todo.completed));
break;
case completed:
setFilteredTodos(todos.filter(todo => todo.completed));
break;
}
};

const onFilterChange = (filter: Filters) => {
if (currentFilter === filter) {
return;
}

setCurrentFilter(filter);

handleFilteredTodos(filter);
};

const isAllCompleted = useMemo(() => {
return filteredTodos.every(todo => todo.completed);
}, [filteredTodos]);

const uncompletedCount = useMemo(() => {
return todos.reduce((acc, todo) => (todo.completed ? acc : acc + 1), 0);
}, [todos]);

const completedCount = useMemo(() => {
return todos.length - uncompletedCount;
}, [todos, uncompletedCount]);

const uncompletedIds = useMemo(() => {
return todos.filter(todo => !todo.completed).map(todo => todo.id);
}, [todos]);

const completedIds = useMemo(() => {
return todos.filter(todo => todo.completed).map(todo => todo.id);
}, [todos]);

const clearCompleted = () => {
setTodoIdsForRemoving(
todos.filter(todo => todo.completed).map(todo => todo.id),
);
setIsTodoDeleting(true);
};

const prepareUpdateData = (): [
{ completed?: boolean; title?: string },
number[],
] => {
let idsForChange: number[] = idsForUpdate;
let updateData: { completed?: boolean; title?: string } = {};

if (reasonForUpdate === UpdateReasons.allToggled) {
idsForChange =
typeOfStatusChange === true
? uncompletedIds
: typeOfStatusChange === false
? completedIds
: [];
setIdsForUpdate(idsForChange);
updateData = { completed: typeOfStatusChange ?? undefined };
} else if (reasonForUpdate === UpdateReasons.oneToggled) {
updateData = { completed: typeOfStatusChange ?? undefined };
} else if (reasonForUpdate === UpdateReasons.titleChanged) {
updateData = { title: titleForUpdate };
}

return [updateData, idsForChange];
};

useEffect(() => {
if (reasonForUpdate === null) {
return;
}

const [updateData, idsForChange = []] = prepareUpdateData();

if (idsForChange.length === 0) {
return;
}

Promise.allSettled(
idsForChange.map(id => {
return updateTodo(id, updateData).then(() => id);
}),
)
.then(results => {
const successfulUpdates = results
.filter(result => result.status === 'fulfilled')
.map(result => result.value as number);

setTodos(t =>
t.map(todo => {
if (successfulUpdates.includes(todo.id)) {
return reasonForUpdate === UpdateReasons.titleChanged
? { ...todo, title: titleForUpdate }
: { ...todo, completed: typeOfStatusChange ?? false };
}

return todo;
}),
);
setFilteredTodos(todos);
if (results.some(result => result.status === 'rejected')) {
setCurrentError(Errors.update);
}

if (
reasonForUpdate === UpdateReasons.titleChanged &&
results.every(result => result.status === 'fulfilled')
) {
setTitleSuccess(true);
}
})
.finally(() => {
setIdsForUpdate([]);
setTypeOfStatusChange(null);
setReasonForUpdate(null);
setTitleForUpdate('');
});
}, [reasonForUpdate]);

Check warning on line 216 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

React Hook useEffect has missing dependencies: 'prepareUpdateData', 'titleForUpdate', 'todos', and 'typeOfStatusChange'. Either include them or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setFilteredTodos' needs the current value of 'todos'

useEffect(() => {
if (
!isTodoDeleting ||
!todoIdsForRemoving ||
todoIdsForRemoving.length === 0
) {
return;
}

Promise.allSettled(
todoIdsForRemoving.map(todoId => deleteTodo(todoId).then(() => todoId)),
)
.then(results => {
const successfulDeletes = results
.filter(result => result.status === 'fulfilled')
.map(result => result.value);

setTodos(t => t.filter(todo => !successfulDeletes.includes(todo.id)));

if (results.some(result => result.status === 'rejected')) {
setCurrentError(Errors.delete);
}
})
.finally(() => {
setIsTodoDeleting(false);
setTodoIdsForRemoving([]);
});
}, [isTodoDeleting, todoIdsForRemoving]);

useEffect(() => {
handleFilteredTodos(currentFilter);
}, [todos, currentFilter]);

Check warning on line 249 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

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

useDelayedSetState(needAutoFocus, setNeedAutoFocus, false, 500);

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
todosCount={todos.length}
isAllCompleted={isAllCompleted}
setTitle={setTitle}
setCurrentError={setCurrentError}
isNewTodoAdding={isNewTodoAdding}
isAdded={isAdded}
currentError={currentError}
isTodoDeleting={isTodoDeleting}
setTypeOfStatusChange={setTypeOfStatusChange}
setReasonForUpdate={setReasonForUpdate}
needAutoFocus={needAutoFocus}
/>

<TodoList
filteredTodos={filteredTodos}
loadingTodo={tempTodo}
isNewTodoAdding={isNewTodoAdding}
isTodoDeleting={isTodoDeleting}
setIsTodoDeleting={setIsTodoDeleting}
todoIdsForRemoving={todoIdsForRemoving}
setTodoIdsForRemoving={setTodoIdsForRemoving}
setReasonForUpdate={setReasonForUpdate}
idsForUpdate={idsForUpdate}
setIdsForUpdate={setIdsForUpdate}
setTypeOfStatusChange={setTypeOfStatusChange}
setTitleForUpdate={setTitleForUpdate}
titleSuccess={titleSuccess}
/>

{/* Hide the footer if there are no todos */}
{todos.length > 0 && (
<Footer
uncompletedCount={uncompletedCount}
completedCount={completedCount}
currentFilter={currentFilter}
onFilterChange={onFilterChange}
clearCompleted={clearCompleted}
/>
)}
</div>

{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}
<ErrorNotification currentError={currentError} />
</div>
);
};
Loading
Loading