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

Open
wants to merge 8 commits 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
139 changes: 121 additions & 18 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,129 @@
/* 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, useRef, useState } from 'react';
import { deleteTodos, getTodos, patchTodos } from './api/todos';
import { Todo } from './types/Todo';
import { Filter } from './types/Filter';
import { Error } from './types/Error';
import { ErrorNotification } from './components/ErrorNotification';
import { removeTodoById } from './utils/removeTodoById';
import { TodoList } from './components/TodoList';
import { Header } from './components/Header';
import { Footer } from './components/Footer';

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

const addTodoField = useRef<HTMLInputElement>(null);
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

function showError(message: Error) {
if (errorTimeoutRef.current) {
clearTimeout(errorTimeoutRef.current);
}

setErrorMessage(message);
errorTimeoutRef.current = setTimeout(
() => setErrorMessage(Error.Default),
3000,
);
}

function handleTodoStatusChange(id: number, newStatus: boolean) {
setLoadingTodoIds(prev => [...prev, id]);
const updateStatus = { completed: newStatus };

return patchTodos(id, updateStatus)
.then(fetchedTodo => {
setTodos(prevTodos =>
prevTodos.map(todo =>
todo.id === fetchedTodo.id ? fetchedTodo : todo,
),
);
})
.catch(() => showError(Error.UpdateError))
.finally(() => {
setLoadingTodoIds(prev => prev.filter(idParametr => idParametr !== id));
});
}

function setFocusOnAddInput() {
if (addTodoField.current !== null) {
addTodoField.current.focus();
}
}

useEffect(() => {
getTodos()
.then(fetchedTodos => {
setTodos(fetchedTodos);
setFocusOnAddInput();
})
.catch(() => showError(Error.LoadError));
}, []);

useEffect(() => {
if (!tempTodo) {
setFocusOnAddInput();
}
}, [tempTodo]);

function onDelete(id: number): Promise<void> {
return deleteTodos(id)
.then(() => {
setTodos(prevTodos => removeTodoById(prevTodos, id));
})
.catch(() => showError(Error.DeleteError));
}

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}
handleTodoStatusChange={handleTodoStatusChange}
showError={showError}
setTodos={setTodos}
setTempTodo={setTempTodo}
addTodoField={addTodoField}
tempTodo={tempTodo}
/>

<TodoList
todos={todos}
activeFilter={activeFilter}
handleTodoStatusChange={handleTodoStatusChange}
onDelete={onDelete}
loadingTodoIds={loadingTodoIds}
setLoadingTodoIds={setLoadingTodoIds}
addTodoField={addTodoField}
tempTodo={tempTodo}
setTodos={setTodos}
showError={showError}
/>

{todos.length !== 0 && (
<Footer
todos={todos}
activeFilter={activeFilter}
setActiveFilter={setActiveFilter}
setLoadingTodoIds={setLoadingTodoIds}
onDelete={onDelete}
setFocusOnAddInput={setFocusOnAddInput}
/>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
/>
</div>
);
};
23 changes: 23 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 2148;

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

export const patchTodos = (
Id: number | null,
updateProperty: { title: string } | { completed: boolean },
) => {
return client.patch<Todo>(`/todos/${Id}`, updateProperty);
};

export const postTodos = (newTodo: Todo) => {
return client.post<Todo>(`/todos`, newTodo);
};

export const deleteTodos = (id: number) => {
return client.delete(`/todos/${id}`);
};
33 changes: 33 additions & 0 deletions src/components/ErrorNotification/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { Dispatch, SetStateAction } from 'react';
import cN from 'classnames';
import { Error } from '../../types/Error';

type Props = {
errorMessage: Error;
setErrorMessage: Dispatch<SetStateAction<Error>>;
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => {
return (
<div
data-cy="ErrorNotification"
className={cN('notification is-danger is-light has-text-weight-normal', {
hidden: errorMessage === Error.Default,
})}
>
<button
onClick={() => setErrorMessage(Error.Default)}
data-cy="HideErrorButton"
type="button"
className="delete"
/>
{/* show only one message at a time +++*/}
{errorMessage}
</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';
88 changes: 88 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import { Todo } from '../../types/Todo';
import { Filter } from '../../types/Filter';
import cN from 'classnames';

type Props = {
todos: Todo[];
activeFilter: Filter;
setActiveFilter: Dispatch<SetStateAction<Filter>>;
setLoadingTodoIds: Dispatch<SetStateAction<number[]>>;
onDelete: (id: number) => Promise<void>;
setFocusOnAddInput: () => void;
};

const filterValues = Object.values(Filter);

export const Footer: React.FC<Props> = ({
todos,
activeFilter,
setActiveFilter,
setLoadingTodoIds,
onDelete,
setFocusOnAddInput,
}) => {
const activeCount: number = useMemo(() => {
return todos.reduce((acc, todo) => {
if (todo.completed === false) {
return acc + 1;
}

return acc;
}, 0);
}, [todos]);

const hasCompleted = useMemo(() => {
return todos.some(todo => todo.completed === true);
}, [todos]);

function handleClearCompleted() {
const completedTodoIds = todos.reduce(
(acc, todo) => (todo.completed ? [...acc, todo.id] : acc),
[] as number[],
);

setLoadingTodoIds(completedTodoIds);

const promises = completedTodoIds.map(id => onDelete(id));

Promise.all(promises).then(() => {
setFocusOnAddInput();
});
}

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

<nav className="filter" data-cy="Filter">
{filterValues.map(filter => {
return (
<a
key={filter}
href={`#/${filter === 'All' ? '' : filter}`}
className={cN('filter__link', {
selected: activeFilter === filter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => setActiveFilter(filter)}
>
{filter}
</a>
);
})}
</nav>
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!hasCompleted}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
);
};
1 change: 1 addition & 0 deletions src/components/Footer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Footer';
Loading
Loading