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

Open
wants to merge 6 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
188 changes: 168 additions & 20 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,174 @@
/* eslint-disable max-len */
/* 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 { Todo } from './types/Todo';
import {
addTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import { ErrorType } from './types/ErrorType';
import { FilterStatus } from './types/FilterStatus';
import { TodoList } from './components/TodoList';

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

useEffect(() => {
schyrva marked this conversation as resolved.
Show resolved Hide resolved
(async () => {
try {
const data = await getTodos();

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

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

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

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

const areAllTodosCompleated = useMemo(
() => todos.every(todo => todo.completed),
[todos],
);

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

const onAddTodo = async (todoTitle: string) => {

Choose a reason for hiding this comment

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

Better use name naming conventions for all cases like that (on>handle)

const onAddTodo = async (todoTitle: string) => {

const handleAddTodo = 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 (err) {
setErrorMessage(ErrorType.AddTodo);
inputAddRef?.current?.focus();

Check failure on line 75 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

'inputAddRef' was used before it was defined
throw err;
} 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 (err) {
setErrorMessage(ErrorType.DeleteTodo);
inputAddRef?.current?.focus();

Check failure on line 89 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

'inputAddRef' was used before it was defined
throw err;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
}
};

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 (err) {
setErrorMessage(ErrorType.UpdateTodo);
throw err;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
};

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

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

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

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

const inputAddRef = useRef<HTMLInputElement>(null);

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}
inputRef={inputAddRef}
onToggleAll={onToggleAll}
areAllTodosCompleated={areAllTodosCompleated}
todosLength={todos.length}
/>

{(todos.length > 0 || tempTodo) && (

Choose a reason for hiding this comment

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

You also can use this syntax

  •    {todos.length > 0 && (
    
  •    {!!todos.length && (
    

<>
<TodoList
filteredTodos={filteredTodos}
onRemoveTodo={onRemoveTodo}
onUpdateTodo={onUpdateTodo}
loadingTodoIds={loadingTodoIds}
tempTodo={tempTodo}
/>
<TodoFooter
filterStatus={filterStatus}
setFilterStatus={setFilterStatus}
todosLeft={todosActiveNum}
todosCompleted={todosCompletedNum}
onClearCompleted={onClearCompleted}
/>
</>
)}
</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 = 2157;
schyrva marked this conversation as resolved.
Show resolved Hide resolved

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);
};
schyrva marked this conversation as resolved.
Show resolved Hide resolved
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 { 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';
54 changes: 54 additions & 0 deletions src/components/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Dispatch, SetStateAction } from 'react';

import cn from 'classnames';
import { FilterStatus } from '../../types/FilterStatus';

type Props = {
filterStatus: FilterStatus;
setFilterStatus: Dispatch<SetStateAction<FilterStatus>>;
schyrva marked this conversation as resolved.
Show resolved Hide resolved
todosLeft: number;
todosCompleted: number;
onClearCompleted: () => Promise<void>;
};

export const TodoFooter: React.FC<Props> = ({
filterStatus,
setFilterStatus,
todosLeft,
todosCompleted,
onClearCompleted,
}) => {
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(FilterStatus).map(filter => (
<a
key={filter}
href={`#/${filter === FilterStatus.All ? '' : filter.toLowerCase()}`}
className={cn('filter__link', {
selected: filterStatus === filter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => setFilterStatus(filter)}
>
{filter}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompleted}
disabled={todosCompleted === 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';
79 changes: 79 additions & 0 deletions src/components/TodoHeader/TodoHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { ErrorType } from '../../types/ErrorType';
import cn from 'classnames';

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

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

const onSubmit = async (event: React.FormEvent<HTMLElement>) => {
event.preventDefault();

const trimmedValue = inputValue.trim();

if (!trimmedValue) {
setErrorMessage(ErrorType.EmptyTitle);

return;
}

try {
await onAddTodo(trimmedValue);
setInputValue('');
} catch {}
};

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

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

return (
<header className="todoapp__header">
{todosLength !== 0 && (
schyrva marked this conversation as resolved.
Show resolved Hide resolved
<button
type="button"
className={cn('todoapp__toggle-all', {
active: areAllTodosCompleated,
})}
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 => 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