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
309 changes: 294 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,305 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { ErrorNotification } from './components/ErrorNotification';
import { Footer } from './components/Footer';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { UserWarning } from './UserWarning';
import {
USER_ID,
createTodo,
deleteTodo,
getTodos,
updateTodo,
} from './api/todos';
import { Filter } from './types/Filter';
import { TempTodo } from './types/TempTodo';
import { Todo } from './types/Todo';

const USER_ID = 0;
const TEMP_TODO_ID = 0;

const getFilterFromHash = (): Filter => {
switch (window.location.hash) {
case '#/active':
return 'active';

case '#/completed':
return 'completed';

default:
return 'all';
}
};

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [filter, setFilter] = useState<Filter>(getFilterFromHash);
const [newTodoTitle, setNewTodoTitle] = useState('');
const [tempTodo, setTempTodo] = useState<TempTodo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [editingTodoId, setEditingTodoId] = useState<number | null>(null);
const [editingTitle, setEditingTitle] = useState('');

const newTodoField = useRef<HTMLInputElement>(null);
const errorTimerId = useRef<number | null>(null);
const editingCanceled = useRef(false);

const hideError = React.useCallback(() => {
setErrorMessage('');

if (errorTimerId.current) {
window.clearTimeout(errorTimerId.current);
errorTimerId.current = null;
}
}, []);

const showError = React.useCallback(
(message: string) => {
hideError();
setErrorMessage(message);

errorTimerId.current = window.setTimeout(() => {
setErrorMessage('');
errorTimerId.current = null;
}, 3000);
},
[hideError],
);

const markTodoAsLoading = (todoId: number) => {
setLoadingTodoIds(currentIds => [...currentIds, todoId]);
};

const unmarkTodoAsLoading = (todoId: number) => {
setLoadingTodoIds(currentIds => currentIds.filter(id => id !== todoId));
};

useEffect(() => {
const handleHashChange = () => setFilter(getFilterFromHash());

window.addEventListener('hashchange', handleHashChange);

return () => {
window.removeEventListener('hashchange', handleHashChange);
};
}, []);

useEffect(() => {
hideError();

getTodos()
.then(setTodos)
.catch(() => showError('Unable to load todos'));

return () => {
if (errorTimerId.current) {
window.clearTimeout(errorTimerId.current);
}
};
}, [hideError, showError]);

useEffect(() => {
newTodoField.current?.focus();
}, [todos.length, tempTodo, errorMessage]);

const visibleTodos = useMemo(() => {
return todos.filter(todo => {
switch (filter) {
case 'active':
return !todo.completed;

case 'completed':
return todo.completed;

default:
return true;
}
});
}, [todos, filter]);

const activeTodosCount = todos.filter(todo => !todo.completed).length;
const completedTodosCount = todos.length - activeTodosCount;
const allTodosCompleted = todos.length > 0 && activeTodosCount === 0;
const isAdding = Boolean(tempTodo);

const handleAddTodo = (event: React.FormEvent) => {
event.preventDefault();

const trimmedTitle = newTodoTitle.trim();

if (!trimmedTitle) {
showError('Title should not be empty');

return;
}

hideError();
setTempTodo({
id: TEMP_TODO_ID,
userId: USER_ID,
title: trimmedTitle,
completed: false,
});

createTodo(trimmedTitle)
.then(todo => {
setTodos(currentTodos => [...currentTodos, todo]);
setNewTodoTitle('');
})
.catch(() => showError('Unable to add a todo'))
.finally(() => setTempTodo(null));
};

const handleDeleteTodo = (todoId: number) => {
hideError();
markTodoAsLoading(todoId);

return deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(error => {
showError('Unable to delete a todo');
throw error;
})
.finally(() => unmarkTodoAsLoading(todoId));
};

const handleUpdateTodo = (todoId: number, data: Partial<Todo>) => {
hideError();
markTodoAsLoading(todoId);

return updateTodo(todoId, data)
.then(updatedTodo => {
setTodos(currentTodos =>
currentTodos.map(todo => (todo.id === todoId ? updatedTodo : todo)),
);
})
.catch(error => {
showError('Unable to update a todo');
throw error;
})
.finally(() => unmarkTodoAsLoading(todoId));
};

const handleToggleTodo = (todo: Todo) => {
handleUpdateTodo(todo.id, { completed: !todo.completed }).catch(() => {});
};

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

todos
.filter(todo => todo.completed !== newCompletedStatus)
.forEach(todo => {
handleUpdateTodo(todo.id, { completed: newCompletedStatus }).catch(
() => {},
);
});
};

const startEditing = (todo: Todo | TempTodo) => {
if (todo.id === TEMP_TODO_ID) {
return;
}

editingCanceled.current = false;
setEditingTodoId(todo.id);
setEditingTitle(todo.title);
};

const cancelEditing = () => {
editingCanceled.current = true;
setEditingTodoId(null);
setEditingTitle('');
};

const submitTodoTitle = (todo: Todo) => {
if (editingCanceled.current) {
editingCanceled.current = false;

return;
}

const trimmedTitle = editingTitle.trim();

if (trimmedTitle === todo.title) {
cancelEditing();

return;
}

if (!trimmedTitle) {
handleDeleteTodo(todo.id)
.then(cancelEditing)
.catch(() => {});

return;
}

handleUpdateTodo(todo.id, { title: trimmedTitle })
.then(cancelEditing)
.catch(() => {});
};

const handleClearCompleted = () => {
todos
.filter(todo => todo.completed)
.forEach(todo => {
handleDeleteTodo(todo.id).catch(() => {});
});
};

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
todosCount={todos.length}
allTodosCompleted={allTodosCompleted}
newTodoTitle={newTodoTitle}
isAdding={isAdding}
newTodoField={newTodoField}
onAddTodo={handleAddTodo}
onNewTodoTitleChange={setNewTodoTitle}
onToggleAll={handleToggleAll}
/>

{(todos.length > 0 || tempTodo) && (
<TodoList
todos={visibleTodos}
tempTodo={tempTodo}
tempTodoId={TEMP_TODO_ID}
loadingTodoIds={loadingTodoIds}
editingTodoId={editingTodoId}
editingTitle={editingTitle}
onToggleTodo={handleToggleTodo}
onDeleteTodo={todoId => handleDeleteTodo(todoId).catch(() => {})}
onStartEditing={startEditing}
onEditingTitleChange={setEditingTitle}
onCancelEditing={cancelEditing}
onSubmitTodoTitle={submitTodoTitle}
/>
)}

{todos.length > 0 && (
<Footer
activeTodosCount={activeTodosCount}
completedTodosCount={completedTodosCount}
filter={filter}
onClearCompleted={handleClearCompleted}
/>
)}
</div>

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

export const USER_ID = 4351;

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

export const createTodo = (title: string) => {
return client.post<Todo>('/todos', {
userId: USER_ID,
title,
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);
};
27 changes: 27 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';

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

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