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

add solution (part 3) #1566

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
194 changes: 175 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,182 @@
/* 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, useRef, useState } from 'react';
import { TodoHeader } from './Components/TodoHeader';
import { TodoFooter } from './Components/TodoFooter';
import { ErrorNotification } from './Components/ErrorNotification';
import {
addTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { ErrorType } from './types/ErrorType';
import { Filter } from './types/Filter';
import { TodoList } from './Components/TodoList';

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

const addTodoInputRef = useRef<HTMLInputElement>(null);

const filteredTodos = useMemo(
() =>
todos.filter(todo => {
switch (filterStatus) {
case Filter.Active:
return !todo.completed;
case Filter.Completed:
return todo.completed;
case Filter.All:
default:
return true;
}
}),
[todos, filterStatus],
);

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

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

const isAllCompleted = useMemo(
() => todos.length === completedTodosLeft,
[todos, completedTodosLeft],
);

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

setTodos(data);
} catch (err) {
setErrorMessage(ErrorType.LoadTodos);
}
})();
}, []);

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

try {
const newTodo = await addTodo({ title: todoTitle, completed: false });

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

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.DeleteTodo);
addTodoInputRef?.current?.focus();
throw error;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
}
};

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(prevTodos =>
prevTodos.map(todo =>
todo.id === updatedTodo.id ? updatedTodo : todo,
),
);
} catch (error) {
setErrorMessage(ErrorType.UpdateTodo);
throw error;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
};

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

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

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}
isInputDisabled={!!tempTodo}
onToggleAll={onToggleAll}
todosLength={todos.length}
isAllCompleted={isAllCompleted}
inputRef={addTodoInputRef}
/>

{(!!todos.length || tempTodo) && (
<>
<TodoList
filteredTodos={filteredTodos}
loadingTodoIds={loadingTodoIds}
tempTodo={tempTodo}
removeTodo={onRemoveTodo}
updateTodo={onUpdateTodo}
/>

<TodoFooter
filterStatus={filterStatus}
setFilterStatus={setFilterStatus}
todosLeft={uncompletedTodosLeft}
completedTodosLeft={completedTodosLeft}
onClearCompleted={onClearCompleted}
/>
</>
)}
</div>

<ErrorNotification error={errorMessage} setError={setErrorMessage} />
</div>
);
};
41 changes: 41 additions & 0 deletions src/Components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
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> = ({ error, setError }) => {
useEffect(() => {
if (error === ErrorType.Empty) {
return;
}

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

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

return (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: error === ErrorType.Empty,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(ErrorType.Empty)}
/>
{error}
</div>
);
};
1 change: 1 addition & 0 deletions src/Components/ErrorNotification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorNotification';
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 cn from 'classnames';
import { Filter } from '../../types/Filter';

type Props = {
filterStatus: Filter;
setFilterStatus: Dispatch<SetStateAction<Filter>>;
todosLeft: number;
completedTodosLeft: number;
onClearCompleted: () => Promise<void>;
};

export const TodoFooter: React.FC<Props> = props => {
const {
filterStatus,
setFilterStatus,
todosLeft,
onClearCompleted,
completedTodosLeft,
} = props;

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

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

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompleted}
disabled={completedTodosLeft === 0}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/Components/TodoFooter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoFooter';
73 changes: 73 additions & 0 deletions src/Components/TodoHeader/TodoHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { ErrorType } from '../../types/ErrorType';
import cn from 'classnames';

type Props = {
todosLength: number;
onAddTodo: (value: string) => Promise<void>;
setErrorMessage: Dispatch<SetStateAction<ErrorType>>;
isInputDisabled: boolean;
isAllCompleted: boolean;
onToggleAll: () => Promise<void>;
inputRef: React.RefObject<HTMLInputElement> | null;
};

export const TodoHeader: React.FC<Props> = ({
todosLength,
onAddTodo,
setErrorMessage,
isInputDisabled,
isAllCompleted,
onToggleAll,
inputRef,
}) => {
const [inputValue, setInputValue] = useState('');

const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (inputValue.trim() === '') {
setErrorMessage(ErrorType.EmptyTodoTitle);

return;
}

try {
await onAddTodo(inputValue.trim());
setInputValue('');
} catch (error) {}
};

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

return (
<header className="todoapp__header">
{todosLength > 0 && (
<button
type="button"
className={cn('todoapp__toggle-all', { active: isAllCompleted })}
data-cy="ToggleAllButton"
onClick={onToggleAll}
/>
)}

<form onSubmit={onSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
ref={inputRef}
value={inputValue}
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setInputValue(event.target.value)
}
disabled={isInputDisabled}
/>
</form>
</header>
);
};
1 change: 1 addition & 0 deletions src/Components/TodoHeader/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TodoHeader';
Loading
Loading