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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
195 changes: 176 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,183 @@
/* 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, useMemo, useState, useRef } from 'react';
import {
addTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import { TodoList } from './components/TodoList/TodoList';
import { Todo } from './types/Todo';
import { TodoFooter } from './components/TodoFooter/TodoFooter';
import { ErrorType } from './types/ErrorType';
// eslint-disable-next-line max-len
import { ErrorNotification } from './components/ErrorNotification/ErrorNotification';
import { TodoHeader } from './components/TodoHeader/TodoHeader';
import { FilterStatus } from './types/FilterStatus';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todos, setTodos] = useState<Todo[]>([]);
const [filterStatus, setFilterStatus] = useState<FilterStatus>(
FilterStatus.All,
);
const [errorMessage, setErrorMessage] = useState<ErrorType>(ErrorType.Empty);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

const inputRef = useRef<HTMLInputElement>(null);

const filteredTodos = useMemo(
() =>
todos.filter(todo => {
if (filterStatus === FilterStatus.All) {
return true;
}

Choose a reason for hiding this comment

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

You don't need to filter at all when filterStatus === FilterStatus.All

return filterStatus === FilterStatus.Completed
? todo.completed
: !todo.completed;
}),

[todos, filterStatus],
);

const activeTodosCount = useMemo(
() => todos.filter(todo => !todo.completed).length,
[todos],
);
const completedTodosCount = useMemo(
() => todos.filter(todo => todo.completed).length,
[todos],
);
const areAllTodosCompleted = useMemo(
() => todos.every(todo => todo.completed),
[todos],
);

Comment on lines +43 to +54

Choose a reason for hiding this comment

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

these three functions will work without useMemo, but they are also very good there

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

setTodos(prev => [...prev, newTodo]);
} catch (error) {
setErrorMessage(ErrorType.UnableToAdd);
throw error;
} finally {
setTempTodo(null);
if (inputRef.current) {
inputRef.current.focus();
}
}
};

const onRemoveTodo = async (todoId: number) => {
setLoadingTodoIds(prev => [...prev, todoId]);

try {
await deleteTodo(todoId);

setTodos(prev => prev.filter(todo => todo.id !== todoId));
} catch (error) {
setErrorMessage(ErrorType.UnableToDelete);
throw error;
} finally {
if (inputRef.current) {
inputRef.current.focus();
}
}
};

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

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

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

setTodos(prev =>
prev.map(todo => (todo.id === updatedTodo.id ? updatedTodo : todo)),
);
} catch (error) {
setErrorMessage(ErrorType.UnableToUpdate);
throw error;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
};

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

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

useEffect(() => {
(async () => {
try {
const data = await getTodos();

setTodos(data);
} catch (error) {
setErrorMessage(ErrorType.UnableToLoad);
}
})();
}, []);

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}
setErrorMessage={setErrorMessage}
inputRef={inputRef}
onToggleAll={onToggleAll}
todosLength={todos.length}
areAllTodosCompleted={areAllTodosCompleted}
/>
{(todos.length > 0 || tempTodo) && (
<>
<TodoList
todos={filteredTodos}
tempTodo={tempTodo}
onRemoveTodo={onRemoveTodo}
onUpdateTodo={onUpdateTodo}
loadingTodoIds={loadingTodoIds}
/>
<TodoFooter
activeTodosCount={activeTodosCount}
setFilter={setFilterStatus}
filter={filterStatus}
onClearCompleted={onClearCompleted}
completedTodosCount={completedTodosCount}
/>
</>
)}
</div>
<ErrorNotification error={errorMessage} setError={setErrorMessage} />
</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 = 2162;

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

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

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

export const updateTodo = (todo: Todo) => {
return client.patch<Todo>(`/todos/${todo.id}`, todo);
};
59 changes: 59 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React, { Dispatch, SetStateAction, useEffect, useState } 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;

const [isHidden, setIsHidden] = useState(true);

useEffect(() => {
if (error === ErrorType.Empty) {
setIsHidden(true);

return;
}

setIsHidden(false);

const timerId = setTimeout(() => {
setError(ErrorType.Empty);
setIsHidden(true);
}, 3000);

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

const handleClose = () => {
setIsHidden(true);
setError(ErrorType.Empty);
};

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

type Props = {
activeTodosCount: number;
setFilter: Dispatch<SetStateAction<FilterStatus>>;
filter: FilterStatus;
onClearCompleted: () => Promise<void>;
completedTodosCount: number;
};

export const TodoFooter: React.FC<Props> = props => {
const {
activeTodosCount,
setFilter,
filter,
onClearCompleted,
completedTodosCount,
} = props;

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

<nav className="filter" data-cy="Filter">
{Object.values(FilterStatus).map(status => (
<a
key={status}
href={`#/${status === FilterStatus.All ? '' : status.toLowerCase()}`}
className={cn('filter__link', {
selected: filter === status,
})}
data-cy={`FilterLink${status}`}
onClick={() => setFilter(status)}
>
{status}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompleted}
disabled={completedTodosCount === 0}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading