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 #799

Open
wants to merge 15 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,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://Sancz0pansa.github.io/react_todo-app-with-api/) and add it to the PR description.
22 changes: 15 additions & 7 deletions cypress/integration/page.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ describe('', () => {

cy.wait('@createRequest2');
page.flushJSTimers();

cy.wait(300);
todos.assertCount(6);
todos.assertNotLoading(5);
todos.assertNotCompleted(5);
Expand Down Expand Up @@ -735,7 +735,7 @@ describe('', () => {

todos.deleteButton(0).click();
cy.wait('@deleteRequest');

cy.wait(500);
errorMessage.assertVisible();
errorMessage.assertText('Unable to delete a todo');
});
Expand Down Expand Up @@ -870,6 +870,7 @@ describe('', () => {
});

it('should show an error message if any of the group deletions fails', () => {
cy.wait(500);
errorMessage.assertVisible();
errorMessage.assertText('Unable to delete a todo');
});
Expand Down Expand Up @@ -1179,6 +1180,7 @@ describe('', () => {
});

it('should make all todos active', () => {
cy.wait(500);
todos.assertNotCompleted(0);
todos.assertNotCompleted(1);
todos.assertNotCompleted(2);
Expand All @@ -1187,6 +1189,7 @@ describe('', () => {
});

it('should become not active', () => {
cy.wait(500);
page.toggleAllButton().should('not.have.class', 'active');
});
});
Expand Down Expand Up @@ -1238,6 +1241,7 @@ describe('', () => {
});

it('should make all todos completed', () => {
cy.wait(500);
todos.assertCompleted(0);
todos.assertCompleted(1);
todos.assertCompleted(2);
Expand All @@ -1246,6 +1250,7 @@ describe('', () => {
});

it('should become active', () => {
cy.wait(500);
page.toggleAllButton().should('have.class', 'active');
});
});
Expand Down Expand Up @@ -1294,12 +1299,14 @@ describe('', () => {
});

it('should send requests only for not completed todos', () => {
cy.wait(500);
cy.get('@update4').should('not.be.called');
cy.get('@update5').should('not.be.called');
cy.get('@update6').should('not.be.called');
});

it('should make all todos completed', () => {
cy.wait(500);
todos.assertCompleted(0);
todos.assertCompleted(1);
todos.assertCompleted(2);
Expand All @@ -1308,6 +1315,7 @@ describe('', () => {
});

it('should become active', () => {
cy.wait(500);
page.toggleAllButton().should('have.class', 'active');
});
});
Expand Down Expand Up @@ -1465,7 +1473,7 @@ describe('', () => {
it('should cancel loading', () => {
todos.titleField(0).type('123{enter}');
cy.wait('@renameRequest');

cy.wait(500);
todos.assertNotLoading(0);
});

Expand All @@ -1480,14 +1488,14 @@ describe('', () => {
it('should show the updated title', () => {
todos.titleField(0).type('Something{enter}');
cy.wait('@renameRequest')

cy.wait(500);
todos.assertTitle(0, 'Something');
});

it('should show trim the new title', () => {
todos.titleField(0).type(' Some new title {enter}');
cy.wait('@renameRequest')

cy.wait(500);
todos.assertTitle(0, 'Some new title');
});
});
Expand Down Expand Up @@ -1607,7 +1615,7 @@ describe('', () => {

todos.titleField(0).type('{enter}');
cy.wait('@deleteRequest');

cy.wait(500);
errorMessage.assertVisible();
errorMessage.assertText('Unable to delete a todo')
});
Expand Down Expand Up @@ -1652,7 +1660,7 @@ describe('', () => {
todos.titleField(0).type('New title');
todos.titleField(0).blur();
cy.wait('@renameRequest')

cy.wait(500)
todos.assertTitle(0, 'New title');
});

Expand Down
238 changes: 226 additions & 12 deletions src/App.tsx
Copy link

Choose a reason for hiding this comment

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

I think most of the code belongs to global state - this should not be in App.tsx file

Original file line number Diff line number Diff line change
@@ -1,24 +1,238 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
/* eslint-disable no-param-reassign */

import React, {
FormEventHandler, useEffect, useRef, useState,
} from 'react';
import cn from 'classnames';
import { UserWarning } from './UserWarning';
import {
addTodo, updateTodo, deleteTodo, getTodos,
} from './api/todos';
import { Todo } from './types/Todo';
import { Filter } from './types/Filter';
import { ErrorMess } from './types/Error';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { NewTodoInput } from './components/NewTodoInput';

const USER_ID = 0;
const USER_ID = 10521;

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [error, setError] = useState<ErrorMess>(null);
const [filter, setFilter] = useState<Filter>('All');
const [title, setTitle] = useState<string>('');
const [temporaryTodo, setTemporaryTodo] = useState<Todo | null>(null);
const [isSubmiting, setIsSubmiting] = useState<boolean>(false);
const [counter, setCounter] = useState<number>(0);
const inputRef = useRef<HTMLInputElement | null>(null);

const handleError = (mess: ErrorMess) => {
setError(mess);
setTimeout(() => setError(null), 3000);
};

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

const fetchData = async () => {
try {
const todoss = getTodos(USER_ID);
const count = (await todoss).filter(todo => todo.completed === false)
.length;

setTodos(await todoss);
setCounter(count);
} catch (e) {
handleError('Unable to load todos');
}
};

const handleCount = () => {
const count = todos.filter(toDo => toDo.completed === false)
.length;

setCounter(count);
};

const handleComplete = (todo: Todo, callback: () => void) => {
updateTodo(todo.id, {
completed: !todo.completed,
}).then(() => {
todo.completed = !todo.completed;
handleCount();
}).catch(() => {
handleError('Unable to update a todo');
}).finally(() => callback());
};

const handleCompleteALL = (toDos: Todo[], data: boolean) => {
toDos.forEach(todo => {
if (data === true && todo.completed === false) {
updateTodo(todo.id, {
completed: data,
}).catch(() => {
handleError('Unable to update a todo');
}).finally(() => {
fetchData();
handleCount();
});
} else if (data === false) {
updateTodo(todo.id, {
completed: data,
}).catch(() => {
handleError('Unable to update a todo');
}).finally(() => {
fetchData();
handleCount();
});
}
});
};

const handleDelete = (todo: Todo, callback?: () => void) => {
deleteTodo(todo.id).then(() => {
setTodos(prevTodo => prevTodo.filter(toDo => toDo !== todo));
inputRef.current?.focus();
fetchData();
}).catch(() => {
handleError('Unable to delete todo');
if (callback) {
callback();
}
});
};

const handleAdd = () => {
setIsSubmiting(true);
addTodo({
id: 0,
userId: USER_ID,
title: title.trim(),
completed: false,
}).then((response) => {
setTitle('');
setCounter(oldCount => oldCount + 1);
setTodos((prevTodos) => [...prevTodos, response] as Todo[]);
}).catch(() => {
handleError('Unable to add a todo');
}).finally(() => {
setTemporaryTodo(null);
setIsSubmiting(false);
});
};

const handleSubmit: FormEventHandler = (e) => {
e.preventDefault();
if (title.trim() === '') {
handleError('Title should not be empty');

return;
}

handleAdd();

setTemporaryTodo({
id: 0,
userId: USER_ID,
title: title.trim(),
completed: false,
});
};

useEffect(() => {
fetchData();
}, []);

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 buttons is active only if there are some active todos */}
{todos.length > 0 && (
<button
type="button"
className={cn('todoapp__toggle-all',
{ active: todos.every(todo => todo.completed) })}
data-cy="ToggleAllButton"
onClick={() => {
if (todos.every(todo => todo.completed === true)) {
handleCompleteALL(todos, false);
} else {
handleCompleteALL(todos, true);
}
}}
/>
)}

{/* Add a todo on form submit */}
<NewTodoInput
handleSubmit={handleSubmit}
title={title}
isSubmiting={isSubmiting}
setTitle={(e) => setTitle(e)}
inputRef={inputRef}
/>
</header>

{(todos.length > 0 || temporaryTodo) && (
<TodoList
todos={todos}
filter={filter}
temporaryTodo={temporaryTodo}
handleDelete={handleDelete}
handleComplete={handleComplete}
handleError={handleError}
/>
)}

{/* Hide the footer if there are no todos */}
{(todos.length > 0 || temporaryTodo)
&& (
<Footer
counter={counter}
filter={filter}
setFilter={(f) => setFilter(f)}
todos={todos}
handleDelete={handleDelete}
/>
)}
</div>

{/* Notification is shown in case of any error */}
{/* Add the 'hidden' class to hide the message smoothly */}
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal',
{ hidden: error === null })}
>
{error
&& (
<div
className="notification is-danger is-light has-text-weight-normal"
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(null)}
/>
</div>

)}
{/* show only one message at a time */}
{error}
</div>
</div>
);
};
Loading