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

solution1 #1576

Open
wants to merge 1 commit 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
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
153 changes: 137 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,147 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
addTodos,
deleteTodos,
getTodos,
updateTodos,
USER_ID,
} from './api/todos';
import { TodoHeader } from './components/TodoHeader';
import { TodoFooter } from './components/TodoFooter';
import { TodoList } from './components/TodoList';
import { Todo } from './types/Todo';
import { Filters } from './types/Filters';
import { ErrorNotification } from './components/ErrorNotification';
import { filterTodos } from './utils/filterTodos';
import { ErrorType } from './types/ErrorType';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorTodos, setErrorTodos] = useState<ErrorType>(ErrorType.Empty);
const [currentFilter, setCurrentFilter] = useState<Filters>(Filters.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodosIds, setLoadingTodosIds] = useState<number[]>([]);

const filtered = useMemo(
() => filterTodos(todos, currentFilter),
[todos, currentFilter],
);

const activeTodos = useMemo(
() => todos.filter(todo => !todo.completed).length,
[todos],
);

const onAddTodo = async (todoTitle: string) => {
setTempTodo({ id: 0, title: todoTitle, completed: false, userId: USER_ID });
try {
const newTodo = await addTodos({ title: todoTitle, completed: false });

setTodos(prev => [...prev, newTodo]);
} catch (err) {
setErrorTodos(ErrorType.AddTodo);
throw err;
} finally {
setTempTodo(null);
}
};

const onDeleteTodo = async (todoId: number) => {
setLoadingTodosIds(prev => [...prev, todoId]);
try {
await deleteTodos(todoId);

setTodos(prev => prev.filter(todo => todo.id !== todoId));
} catch (err) {
setErrorTodos(ErrorType.DeleteTodo);
throw err;
} finally {
setLoadingTodosIds(prev => prev.filter(id => id !== todoId));
}
};

const onUpdateTodo = async (todoToUpdate: Todo) => {
setLoadingTodosIds(prev => [...prev, todoToUpdate.id]);
try {
const updatedTodo = await updateTodos(todoToUpdate);

setTodos(prev =>
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)),
);
} catch (err) {
setErrorTodos(ErrorType.UpdateTodo);
throw err;
} finally {
setLoadingTodosIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
};

const onToggleAll = async () => {
if (activeTodos > 0) {
const thisTodos = todos.filter(todo => !todo.completed);

thisTodos.forEach(todo => {
onUpdateTodo({ ...todo, completed: true });
});
} else {
todos.forEach(todo => {
onUpdateTodo({ ...todo, completed: false });
});
}
};

const handleClearCompleted = async () => {
const completedTodos = todos.filter(todo => todo.completed);

completedTodos.forEach(todo => {
onDeleteTodo(todo.id);
});
};

useEffect(() => {
getTodos()
.then(data => setTodos(data))
.catch(() => setErrorTodos(ErrorType.LoadTodo));
}, []);

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">
<TodoHeader
onAddTodo={onAddTodo}
setErrorTodos={setErrorTodos}
onToggleAll={onToggleAll}
isAllCompleted={todos.every(todo => todo.completed)}
/>

{todos.length > 0 && (
<>
<TodoList
todos={filtered}
onDeleteTodos={onDeleteTodo}
loadingTodosIds={loadingTodosIds}
onUpdateTodo={onUpdateTodo}
tempTodo={tempTodo}
/>

<TodoFooter
todos={todos}
currentFilter={currentFilter}
setCurrentFilter={setCurrentFilter}
handleClearCompleted={handleClearCompleted}
activeTodos={activeTodos}
/>
</>
)}
</div>
<ErrorNotification error={errorTodos} setError={setErrorTodos} />
</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 = 2183;

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

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

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

export const updateTodos = (todo: Todo) => {
return client.patch<Todo>(`/todos/${todo.id}`, todo);
};
40 changes: 40 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React, { Dispatch, SetStateAction, useEffect } from 'react';
import cn from 'classnames';
import { ErrorType } from '../types/ErrorType';
type Props = {
error: ErrorType;
setError: Dispatch<SetStateAction<ErrorType>>;
};

export const ErrorNotification: React.FC<Props> = props => {
const { error, setError } = props;

useEffect(() => {
if (error === ErrorType.Empty) {
return;
}

const timer = setTimeout(() => {
setError(ErrorType.Empty);
}, 3000);

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

return (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !error,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(ErrorType.Empty)}
/>
{error}
</div>
);
};
73 changes: 73 additions & 0 deletions src/components/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React, { Dispatch, SetStateAction } from 'react';
import { Todo } from '../types/Todo';
import { Filters } from '../types/Filters';
import cn from 'classnames';

type Props = {
currentFilter: Filters;
setCurrentFilter: Dispatch<SetStateAction<Filters>>;
todos: Todo[];
handleClearCompleted: () => Promise<void>;
activeTodos: number;
};

const filters = [
{ name: 'All', href: '#/', filter: Filters.All, dataCy: 'FilterLinkAll' },
{
name: 'Active',
href: '#/active',
filter: Filters.Active,
dataCy: 'FilterLinkActive',
},
{
name: 'Completed',
href: '#/completed',
filter: Filters.Completed,
dataCy: 'FilterLinkCompleted',
},
];

export const TodoFooter: React.FC<Props> = props => {
const {
todos,
handleClearCompleted,
currentFilter,
setCurrentFilter,
activeTodos,
} = props;
// const activeTodos = todos.filter(todo => !todo.completed);

Choose a reason for hiding this comment

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

Remove all comments


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

<nav className="filter" data-cy="Filter">
{filters.map(({ name, href, filter, dataCy }) => (
<a
key={filter}
href={href}
className={cn('filter__link', {
selected: currentFilter === filter,
})}
data-cy={dataCy}
onClick={() => setCurrentFilter(filter)}
>
{name}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={todos.every(todo => !todo.completed)}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading