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://aholubko.github.io/react_todo-app-with-api/) and add it to the PR description.
270 changes: 256 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,268 @@
/* 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, { useEffect, useRef, useState } from 'react';
import { UserWarning } from './UserWarning';
import {
addTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';

const USER_ID = 0;
import { FilterBy } from './types/FilterBy';
import { TodoFooter } from './components/TodoFooter';
import { ErrorNotification } from './components/ErrorNotification';
import { TodoHeader } from './components/TodoHeader';
import { TodoItem } from './components/TodoItem';

export const App: React.FC = () => {
//#region State
const [todos, setTodos] = useState<Todo[]>([]);
const [filterBy, setFilterBy] = useState(FilterBy.All);
const [errorMessage, setErrorMessage] = useState('');

const [title, setTitle] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [isAdding, setIsAdding] = useState(false);
const [processingIds, setProcessingIds] = useState<number[]>([]);
//#endregion

//#region Refs
const inputRef = useRef<HTMLInputElement>(null);
//#endregion

//#region Derived values
const activeTodosCount = todos.filter(todo => !todo.completed).length;
const completedTodosCount = todos.filter(todo => todo.completed).length;
const allCompleted = todos.length > 0 && activeTodosCount === 0;

let visibleTodos = todos;

if (filterBy === FilterBy.Active) {
visibleTodos = visibleTodos.filter(todo => !todo.completed);
}

if (filterBy === FilterBy.Completed) {
visibleTodos = visibleTodos.filter(todo => todo.completed);
}
//#endregion

//#region Handlers
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();

if (title.trim() === '') {
setErrorMessage('Title should not be empty');

return;
}

const newTempTodo = {
id: 0,
title: title.trim(),
completed: false,
userId: USER_ID,
};

setErrorMessage('');
setIsAdding(true);

setTempTodo(newTempTodo);

addTodo(title.trim())
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setTitle('');
setTempTodo(null);
})
.catch(() => {
setErrorMessage('Unable to add a todo');
setTempTodo(null);
})
.finally(() => {
setIsAdding(false);
setTimeout(() => {
inputRef.current?.focus();
}, 0);
});
};

const handleDelete = (todoId: number) => {
setErrorMessage('');

setProcessingIds(currentIds => [...currentIds, todoId]);

return deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage('Unable to delete a todo');
})
.finally(() => {
setProcessingIds(currentIds => currentIds.filter(id => id !== todoId));
setTimeout(() => {
inputRef.current?.focus();
}, 0);
});
};

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

return Promise.all(completedTodos.map(todo => handleDelete(todo.id)));
};

const handleToggle = (todo: Todo) => {
const newCompletedStatus = !todo.completed;

setErrorMessage('');

setProcessingIds(currentIds => [...currentIds, todo.id]);

return updateTodo(todo.id, { completed: newCompletedStatus })
.then(updatedTodo => {
setTodos(currentTodos =>
currentTodos.map(currentTodo =>
currentTodo.id === todo.id ? updatedTodo : currentTodo,
),
);
})
.catch(() => {
setErrorMessage('Unable to update a todo');
})
.finally(() => {
setProcessingIds(currentIds => currentIds.filter(id => id !== todo.id));
});
};

const handleToggleAll = () => {
const newCompletedStatus = !allCompleted;

const todosToUpdate = todos.filter(
todo => todo.completed !== newCompletedStatus,
);

return Promise.all(todosToUpdate.map(todo => handleToggle(todo)));
};

const handleUpdate = (todoId: number, newTitle: string) => {
setErrorMessage('');

setProcessingIds(currentIds => [...currentIds, todoId]);

return updateTodo(todoId, { title: newTitle })
.then(updatedTodo => {
setTodos(currentTodos =>
currentTodos.map(currentTodo =>
currentTodo.id === todoId ? updatedTodo : currentTodo,
),
);
})
.catch(() => {
setErrorMessage('Unable to update a todo');

throw new Error();
})
.finally(() => {
setProcessingIds(currentIds => currentIds.filter(id => id !== todoId));
});
};

//#endregion

//#region Effects
useEffect(() => {
setErrorMessage('');

getTodos()
.then(setTodos)
.catch(() => setErrorMessage('Unable to load todos'));
}, []);

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

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

const timerId = window.setTimeout(() => {
setErrorMessage('');
}, 3000);

return () => {
window.clearTimeout(timerId);
};
}, [errorMessage]);
//#endregion

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">
<TodoHeader
allCompleted={allCompleted}
handleSubmit={handleSubmit}
title={title}
setTitle={setTitle}
isAdding={isAdding}
inputRef={inputRef}
handleToggleAll={handleToggleAll}
hasTodos={todos.length > 0}
/>

{(todos.length > 0 || tempTodo) && (
<section className="todoapp__main" data-cy="TodoList">
{visibleTodos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onDelete={handleDelete}
isProcessing={processingIds.includes(todo.id)}
onToggle={handleToggle}
onUpdate={handleUpdate}
/>
))}

{tempTodo && (
<TodoItem
todo={tempTodo}
onDelete={handleDelete}
isProcessing
onToggle={handleToggle}
onUpdate={handleUpdate}
/>
)}
</section>
)}

{todos.length > 0 && (
<TodoFooter
activeTodosCount={activeTodosCount}
completedTodosCount={completedTodosCount}
filterBy={filterBy}
setFilterBy={setFilterBy}
handleClearCompleted={handleClearCompleted}
/>
)}
</div>

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

export const USER_ID = 4192;

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

// Add more methods here
export const addTodo = (title: string) => {
return client.post<Todo>('/todos', {
userId: USER_ID,
title: title.trim(),
completed: false,
});
};

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

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

type Props = {
errorMessage: string;
setErrorMessage: (value: string) => void;
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => {
return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{
hidden: !errorMessage,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage('')}
/>
{errorMessage}
</div>
);
};
Loading
Loading