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

finishing the chalenge #1517

Open
wants to merge 6 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 @@ -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://italomagno.github.io/react_todo-app-with-api/) and add it to the PR description.
6 changes: 3 additions & 3 deletions cypress/integration/page.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ describe('', () => {
});

// this test may be flaky
it.skip('should replace loader with a created todo', () => {
it('should replace loader with a created todo', () => {
page.flushJSTimers();
todos.assertCount(6);
todos.assertNotLoading(5);
Expand Down Expand Up @@ -1515,7 +1515,7 @@ describe('', () => {
});

// It depend on your implementation
it.skip('should stay while waiting', () => {
it('should stay while waiting', () => {
page.mockUpdate(257334);

todos.title(0).trigger('dblclick');
Expand Down Expand Up @@ -1694,7 +1694,7 @@ describe('', () => {
});

// this test may be unstable
it.skip('should hide loader on fail', () => {
it('should hide loader on fail', () => {
// to prevent Cypress from failing the test on uncaught exception
cy.once('uncaught:exception', () => false);

Expand Down
317 changes: 218 additions & 99 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@
"license": "GPL-3.0",
"dependencies": {
"@fortawesome/fontawesome-free": "^6.5.2",
"@reduxjs/toolkit": "^2.3.0",
"bulma": "^1.0.1",
"classnames": "^2.5.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"react-transition-group": "^4.4.5"
},
"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
115 changes: 99 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,109 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { getTodos, USER_ID } from './api/todos';
import { Todo } from './types/Todo';
import { TodoList } from './components/TodoList';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { ErrorComponent } from './components/ErrorComponent';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [filteredTodos, setFilteredTodos] = useState<Todo[]>([]);
const [error, setError] = useState<string | null>(null);
const [editingTodosId, setEditingTodosId] = useState<number[]>([]);
const [isFooterActive, setIsFooterActiveFilter] = useState(false);
const [filter, setFilter] = useState('all');

Choose a reason for hiding this comment

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

Try to keep the name of the variable and the setter with the same name.


async function loadAllTodos() {
try {
const loadedTodos = await getTodos();

if (loadedTodos.length > 0) {
setIsFooterActiveFilter(true);
}

setTodos(loadedTodos);
setFilteredTodos(loadedTodos);
} catch (e) {
setError('Unable to load todos');
}
}

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

useEffect(() => {
setTimeout(() => {
setError(null);
}, 3000);
}, [error]);

useEffect(() => {
if (todos.length === 0) {
setIsFooterActiveFilter(false);

return;
}

setIsFooterActiveFilter(true);
}, [todos.length]);

useEffect(() => {
if (filter === 'completed') {
setFilteredTodos(prev => prev.filter(t => t.completed));
}

if (filter === 'active') {
setFilteredTodos(prev => prev.filter(t => !t.completed));
}
}, [filter, todos]);

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
todos={todos}
setEditingTodosId={setEditingTodosId}
setError={setError}
editingTodosId={editingTodosId}
setTodos={setTodos}
setFilteredTodos={setFilteredTodos}
filteredTodos={filteredTodos}
/>
<section className="todoapp__main" data-cy="TodoList">
<TodoList
filter={filter}
filteredTodos={filteredTodos}
editingTodosId={editingTodosId}
setEditingTodosId={setEditingTodosId}
setError={setError}
todos={todos}
setTodos={setTodos}
setFilteredTodos={setFilteredTodos}
/>
</section>
<Footer
filter={filter}
setFilter={setFilter}
setFilteredTodos={setFilteredTodos}
todos={todos}
isFooterActive={isFooterActive}
setEditingTodosId={setEditingTodosId}
loadAllTodos={loadAllTodos}
setTodos={setTodos}
setError={setError}
editingTodosId={editingTodosId}
/>
</div>

<ErrorComponent error={error} setError={setError} />
</div>
);
};
24 changes: 24 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 1865;

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

export const addTodo = (title: string) => {
return client.post<Todo>('/todos', {
userId: USER_ID,
title,
completed: false,
});
};

export const updateTodo = (todo: Todo) => {
return client.patch<Todo>(`/todos/${todo.id}`, todo);
};

export const deleteTodo = (id: number) => {
return client.delete(`/todos/${id}`);
};
21 changes: 21 additions & 0 deletions src/components/ErrorComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
interface ErrorComponentProps {
error: string | null;
setError: (error: string | null) => void;
}

export function ErrorComponent({ error, setError }: ErrorComponentProps) {
return (
<div
data-cy={`ErrorNotification`}
className={`notification is-danger is-light has-text-weight-normal ${error ? '' : 'hidden'}`}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(null)}
/>
{error}
</div>
);
}
122 changes: 122 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { deleteTodo } from '../api/todos';
import { Todo } from '../types/Todo';

export interface FooterProps {
todos: Todo[];
isFooterActive: boolean;
setEditingTodosId: (ids: number[]) => void;
loadAllTodos: () => void;
setError: (error: string) => void;
editingTodosId: number[];
setFilteredTodos: (todos: Todo[]) => void;
setTodos: (todos: Todo[]) => void;
filter: string;
setFilter: (filter: string) => void;
}
export function Footer({
todos,
isFooterActive,
setEditingTodosId,
setError,
editingTodosId,
setTodos,
setFilteredTodos,
filter,
setFilter,
}: FooterProps) {
function handleFilterTodos(filterString: string) {
setFilter(filterString);
switch (filterString) {
case 'all':
setFilteredTodos(todos);
break;
case 'active':
setFilteredTodos(todos.filter(t => !t.completed));
break;
case 'completed':
setFilteredTodos(todos.filter(t => t.completed));
break;
default:
setFilteredTodos(todos);
}
}

async function handleDeleteAllCompletedTodos() {
const completedTodos = todos.filter(t => t.completed);
const completedTodoIds = completedTodos.map(t => t.id);

setEditingTodosId([...editingTodosId, ...completedTodoIds]);

const successfulDeletes: number[] = [];

for (const todo of completedTodos) {
try {
await deleteTodo(todo.id);
successfulDeletes.push(todo.id);
} catch (error) {
setError('Unable to delete a todo');
}
}

const newTodos = todos.filter(t => !successfulDeletes.includes(t.id));

setEditingTodosId(
editingTodosId.filter(id => !completedTodoIds.includes(id)),
);
setFilteredTodos(newTodos);
setTodos(newTodos);
}

return (
<>
{isFooterActive && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${todos.filter(t => !t.completed).length} items left`}
</span>

<nav className="filter" data-cy="Filter">
<a
onClick={() => handleFilterTodos('all')}
href="#/"
className={`filter__link ${filter === 'all' ? 'selected' : ''}`}
data-cy="FilterLinkAll"
>
All
</a>

<a
onClick={() => handleFilterTodos('active')}
href="#/active"
className={`filter__link ${filter === 'active' ? 'selected' : ''}`}
data-cy="FilterLinkActive"
>
Active
</a>

<a
onClick={() => {
handleFilterTodos('completed');
}}
href="#/completed"
className={`filter__link ${filter === 'completed' ? 'selected' : ''}`}
data-cy="FilterLinkCompleted"
>
Completed
</a>
</nav>

<button
type="button"
className={`todoapp__clear-completed`}
data-cy="ClearCompletedButton"
disabled={!todos.some(t => t.completed)}
onClick={handleDeleteAllCompletedTodos}
>
Clear completed
</button>
</footer>
)}
</>
);
}
Loading
Loading