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

Develop #1500

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Develop #1500

Show file tree
Hide file tree
Changes from 3 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://HunchakAndrii.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": "^1.9.12",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
85 changes: 66 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,73 @@
/* 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 { UserWarning } from './UserWarning';

const USER_ID = 0;
import React, { useEffect, useState } from 'react';
import { getTodos } from './api/todos';
import { Header } from './components/Header/Header';
import { TodoList } from './components/TodoList/TodoList';
import { Footer } from './components/Footer/Footer';
import { Notification } from './components/NotificationComponent/Notification';
import { Todo } from './types/Todo';
import { filterTodos } from './utils/filterTodos';
import { FilterType } from './types/FilterType';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [error, setError] = useState('');
const [isLoadingIds, setIsLoadingIds] = useState<number[]>([]);
const [currentFilter, setCurrentFilter] = useState<FilterType>(
FilterType.All,
);

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => setError('Unable to load todos'));
}, []);

const resultFilterdTodos = filterTodos(currentFilter, todos);

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}
setTodos={setTodos}
setTempTodo={setTempTodo}
error={error}
setError={setError}
isLoadingIds={isLoadingIds}
setIsLoadingIds={setIsLoadingIds}
/>

{resultFilterdTodos.length > 0 && (
<TodoList
todos={resultFilterdTodos}
setTodos={setTodos}
tempTodo={tempTodo}
setTempTodo={setTempTodo}
setError={setError}
isLoadingIds={isLoadingIds}
setIsLoadingIds={setIsLoadingIds}
/>
)}

{todos.length > 0 && (
<Footer
todos={todos}
setTodos={setTodos}
setCurrentFilter={setCurrentFilter}
setError={setError}
setIsLoadingIds={setIsLoadingIds}
/>
)}
</div>

{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}
<Notification error={error} setError={setError} />
</div>
);
};
29 changes: 29 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClients';

export const USER_ID = 1551;

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

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

export const createTodo = ({ userId, title, completed }: Omit<Todo, 'id'>) => {
return client.post<Todo>('/todos', { userId, title, completed });
};

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

// Add more methods here
98 changes: 98 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { useState } from 'react';
import { FilterType } from '../../types/FilterType';
import classNames from 'classnames';
import { deleteTodo } from '../../api/todos';
import { FooterType } from '../../types/FooterType';

export const Footer: React.FC<FooterType> = ({
todos,
setTodos,
setCurrentFilter,
setError,
setIsLoadingIds,
}) => {
const [activeFilter, setActiveFilter] = useState<string>(FilterType.All);

Choose a reason for hiding this comment

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

Suggested change
const [activeFilter, setActiveFilter] = useState<string>(FilterType.All);
const [activeFilter, setActiveFilter] = useState<FilterType>(FilterType.All);

Choose a reason for hiding this comment

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

why do you need this state here? looks redundant, just pass to the footer the currentFilter


const completedTodos = todos.filter(todo => todo.completed);
const TodoCount = todos.length - completedTodos.length;

const handleFilterChange = (filterType: FilterType) => {
setActiveFilter(filterType);
setCurrentFilter(filterType);
};

const handleClearComplete = () => {
const completedTodoIds = completedTodos.map(todo => todo.id);

setIsLoadingIds(currentIds => [...currentIds, ...completedTodoIds]);

Promise.allSettled(
completedTodoIds.map(id => {
return deleteTodo(id)
.then(() => {
setTodos(currentToDos =>
currentToDos.filter(item => item.id !== id),
);
})
.catch(() => {
setError('Unable to delete a todo');
});
}),
).finally(() => {
setIsLoadingIds([]);
});
};

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{TodoCount} items left
</span>

<nav className="filter" data-cy="Filter">
<a
href="#/"
className={classNames('filter__link', {
selected: activeFilter === FilterType.All,
})}
data-cy="FilterLinkAll"
onClick={() => handleFilterChange(FilterType.All)}
>
All
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: activeFilter === FilterType.Active,
})}
data-cy="FilterLinkActive"
onClick={() => handleFilterChange(FilterType.Active)}
>
Active
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: activeFilter === FilterType.Completed,
})}
data-cy="FilterLinkCompleted"
onClick={() => handleFilterChange(FilterType.Completed)}
>
Completed
</a>
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={completedTodos.length === 0}
onClick={handleClearComplete}
>
Clear completed
</button>
</footer>
);
};
85 changes: 85 additions & 0 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { useEffect, useRef, useState } from 'react';
import { addTodo } from '../../utils/addTodo';
import { toggleCompletedTodo } from '../../utils/toggleTodo';
import classNames from 'classnames';
import { HeaderProps } from '../../types/HeaderProps';

export const Header: React.FC<HeaderProps> = ({
todos,
setTodos,
setTempTodo,
error,
setError,
isLoadingIds,
setIsLoadingIds,
}) => {
const [inputValue, setInputValue] = useState('');

const titleInput = useRef<HTMLInputElement>(null);
const isCompletedAll = todos.every(todo => todo.completed);

useEffect(() => {
titleInput.current?.focus();
}, [todos, error]);

function handleAddTodo(event: React.FormEvent) {
event.preventDefault();

addTodo(
inputValue,
setError,
setTempTodo,
setTodos,
setInputValue,
setIsLoadingIds,
);
}

const completeAllTodo = () => {
const todosToUpdate = isCompletedAll
? todos
: todos.filter(todo => !todo.completed);

const idsToLoad = todosToUpdate.map(todo => todo.id);

setIsLoadingIds(currentIds => [...currentIds, ...idsToLoad]);

setTimeout(() => {
Promise.all(
todosToUpdate.map(todo => {
return toggleCompletedTodo(todo, setIsLoadingIds, setTodos, setError);
}),
).finally(() => {
setIsLoadingIds([]);
});
}, 300);
};

return (
<header className="todoapp__header">
{todos.length > 0 && (
<button
type="button"
className={classNames('todoapp__toggle-all', {
active: isCompletedAll,
})}
data-cy="ToggleAllButton"
onClick={completeAllTodo}
/>
)}

<form onSubmit={handleAddTodo}>
<input
ref={titleInput}
disabled={isLoadingIds.length > 0}
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={inputValue}
onChange={event => setInputValue(event.target.value)}
/>
</form>
</header>
);
};
40 changes: 40 additions & 0 deletions src/components/NotificationComponent/Notification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import classNames from 'classnames';
import { useEffect } from 'react';
import { NotificationProps } from '../../types/NotificationProps';

export const Notification: React.FC<NotificationProps> = ({
error,
setError,
}) => {
useEffect(() => {
let timer: number;

if (error) {
timer = window.setTimeout(() => {
setError('');
}, 3000);
}

return () => {
clearTimeout(timer);
};
}, [error, setError]);

return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: !error },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError('')}
/>
{error}
</div>
);
};
Loading
Loading