Skip to content
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ Implement the ability to edit a todo title on double click:

- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://Yevhen-Srdk.github.io/react_todo-app-with-api/) and add it to the PR description.
221 changes: 206 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,217 @@
/* 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 React, { ChangeEvent, useEffect, useRef, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
addTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { Errors } from './types/ErrorsEnum';
import { FilterValues } from './types/FilterValuesEnum';

export const App: React.FC = () => {
const [todoStatus, setTodoStatus] = useState<FilterValues>(FilterValues.All);
const [title, setTitle] = useState('');
const [todos, setTodos] = useState<Todo[]>([]);
const [loadingIds, setLoadingIds] = useState<number[]>([]);
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const inputFocusRef = useRef<HTMLInputElement>(null);

useEffect(() => {
if (!USER_ID) {
return;
}

inputFocusRef.current?.focus();

getTodos()
.then(todosFromServer => setTodos(todosFromServer))
.catch(() => setError(Errors.unableToLoadTodosError));
}, []);

useEffect(() => {
if (!error) {
return;
}

const timer = setTimeout(() => setError(Errors.clearErrors), 3000);

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

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

const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value);
};

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmedTitle = title.trim();

if (trimmedTitle.length === 0) {
setIsSubmitting(false);
setError(Errors.emptyTitleError);

return;
}

setIsSubmitting(true);
setTempTodo({
id: 0,
title: trimmedTitle,
completed: false,
userId: USER_ID,
});

addTodo({ title: trimmedTitle, completed: false, userId: USER_ID })
.then(newTodo => {
setTodos(prev => [...prev, newTodo]);
setTitle('');
})
.catch(() => {
setError(Errors.unableToAddTodoError);
})
.finally(() => {
setIsSubmitting(false);
setTempTodo(null);
});
};

const handleDeleteTodo = (todoId: number) => {
setLoadingIds(prev => [...prev, todoId]);

deleteTodo(todoId)
.then(() =>
setTodos(currentTodos => {
return currentTodos.filter(todo => todo.id !== todoId);
}),
)
.catch(() => setError(Errors.unableToDeleteATodoError))
.finally(() => {
setLoadingIds(prev => prev.filter(id => id !== todoId));
inputFocusRef.current?.focus();
});
};

const handleUpdateTodo = (updatedTodo: Todo): Promise<void> => {
setLoadingIds(prev => [...prev, updatedTodo.id]);

return updateTodo(updatedTodo)
.then(todo => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(
todoIndex => todoIndex.id === updatedTodo.id,
);

newTodos.splice(index, 1, todo);

return newTodos;
});
})
.catch(e => {
setError(Errors.unableUpdateTodoError);
throw e;
})
.finally(() => {
setLoadingIds(prev => prev.filter(id => id !== updatedTodo.id));
});
};

const handleToggleAll = () => {
const allCompleted = todos.every(todo => todo.completed);
const todosToUpdate = todos.filter(todo => todo.completed === allCompleted);

todosToUpdate.forEach(todo => {
handleUpdateTodo({ ...todo, completed: !allCompleted });
});
};

const handleClearCompletedTodo = () => {
const completedTodos = todos.filter(todo => todo.completed);
const completedIds = completedTodos.map(todo => todo.id);

setLoadingIds(prev => [...prev, ...completedIds]);

Promise.all(
completedIds.map(id =>
deleteTodo(id)
.then(() => setTodos(prev => prev.filter(todo => todo.id !== id)))
.catch(() => setError(Errors.unableToDeleteATodoError))
.finally(() =>
setLoadingIds(prev => prev.filter(loadingId => loadingId !== id)),
),
),
).finally(() => inputFocusRef.current?.focus());
};

const filteredTodos = todos.filter(todo => {
if (todoStatus === FilterValues.All) {
return true;
}

if (todoStatus === FilterValues.Active) {
return !todo.completed;
}

return todo.completed;
});

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">
<Header
todos={todos}
title={title}
handleInputChange={handleInputChange}
handleSubmit={handleSubmit}
handleToggleAll={handleToggleAll}
inputRef={inputFocusRef}
isSubmitting={isSubmitting}
/>

{todos.length > 0 && (
<TodoList
filteredTodos={filteredTodos}
loadingIds={loadingIds}
tempTodo={tempTodo}
handleDeleteTodo={handleDeleteTodo}
updateTodo={handleUpdateTodo}
/>
)}

{todos.length > 0 && (
<Footer
todos={todos}
todoStatus={todoStatus}
setTodoStatus={setTodoStatus}
clearCompletedTodo={handleClearCompletedTodo}
/>
)}
</div>

<ErrorNotification error={error} setError={setError} />
</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 = 4162;

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

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

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

export const updateTodo = ({ id, ...todoData }: Todo) => {
return client.patch<Todo>(`/todos/${id}`, todoData);
};
26 changes: 26 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import classNames from 'classnames';

type Props = {
error: string;
setError: (value: string) => void;
};

export const ErrorNotification = ({ error, setError }: Props) => {
return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: !error },
)}
>
<button
onClick={() => setError('')}
data-cy="HideErrorButton"
type="button"
className="delete"
/>
{error}
</div>
);
};
46 changes: 46 additions & 0 deletions src/components/Filter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import classNames from 'classnames';
import { FilterValues } from '../types/FilterValuesEnum';

type Props = {
todoStatus: FilterValues;
setTodoStatus: (value: FilterValues) => void;
};

export const Filter = ({ todoStatus, setTodoStatus }: Props) => {
return (
<nav className="filter" data-cy="Filter">
<a
href="#/"
className={classNames('filter__link', {
selected: todoStatus === FilterValues.All,
})}
data-cy="FilterLinkAll"
onClick={() => setTodoStatus(FilterValues.All)}
>
All
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: todoStatus === FilterValues.Active,
})}
data-cy="FilterLinkActive"
onClick={() => setTodoStatus(FilterValues.Active)}
>
Active
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: todoStatus === FilterValues.Completed,
})}
data-cy="FilterLinkCompleted"
onClick={() => setTodoStatus(FilterValues.Completed)}
>
Completed
</a>
</nav>
);
};
36 changes: 36 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Todo } from '../types/Todo';
import { TodosCounter } from './TodosCounter';
import { Filter } from './Filter';
import { FilterValues } from '../types/FilterValuesEnum';

type Props = {
todos: Todo[];
todoStatus: FilterValues;
setTodoStatus: (value: FilterValues) => void;
clearCompletedTodo: () => void;
};

export const Footer = ({
todos,
todoStatus,
setTodoStatus,
clearCompletedTodo,
}: Props) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<TodosCounter todos={todos} />

<Filter todoStatus={todoStatus} setTodoStatus={setTodoStatus} />

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