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
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"devDependencies": {
"@cypress/react18": "^2.0.1",
"@mate-academy/scripts": "^1.8.5",
"@mate-academy/scripts": "^2.1.3",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
247 changes: 231 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,241 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames';

import { Todo } from './types/Todo';
import { ErrorMessage } from './types/ErrorMessage';
import { getTodos, addTodo, deleteTodo, updateTodo } from './api/todos';
import { TodoList } from './components/TodoList';
import { TodoFilter, FilterValue } from './components/TodoFilter';
import { ErrorNotification } from './components/ErrorNotification';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
const USER_ID = 2425;

export const App: React.FC = () => {
if (!USER_ID) {
const [todos, setTodos] = useState<Todo[]>([]);
const [filter, setFilter] = useState<FilterValue>('all');
const [errorMessage, setErrorMessage] = useState<ErrorMessage | null>(null);
const [newTitle, setNewTitle] = useState('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);
const [isAdding, setIsAdding] = useState(false);

const inputRef = useRef<HTMLInputElement>(null);

const activeUserId = (() => {
try {
const user = localStorage.getItem('user');

return user ? JSON.parse(user).id : USER_ID;
} catch {
return USER_ID;
}
})();

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

getTodos(activeUserId)
.then(setTodos)
.catch(() => {
setErrorMessage(ErrorMessage.Load);
});
}, [activeUserId]);

useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, [todos, tempTodo]);

if (!activeUserId) {
return <UserWarning />;
}

const handleAddTodo = (e: React.FormEvent) => {
e.preventDefault();
const trimmedTitle = newTitle.trim();

if (!trimmedTitle) {
setErrorMessage(ErrorMessage.EmptyTitle);

return;
}

const optimisticTodo: Todo = {
id: 0,
userId: activeUserId,
title: trimmedTitle,
completed: false,
};

setTempTodo(optimisticTodo);
setIsAdding(true);
setErrorMessage(null);

addTodo({ userId: activeUserId, title: trimmedTitle, completed: false })
.then(newTodo => {
setTodos(prev => [...prev, newTodo]);
setNewTitle('');
})
.catch(() => {
setErrorMessage(ErrorMessage.Add);
})
.finally(() => {
setTempTodo(null);
setIsAdding(false);
inputRef.current?.focus();
});
};

const handleDeleteTodo = (todoId: number): Promise<void> => {
setLoadingTodoIds(prev => [...prev, todoId]);
setErrorMessage(null);

return deleteTodo(todoId)
.then(() => {
setTodos(prev => prev.filter(todo => todo.id !== todoId));
})
.catch(err => {
setErrorMessage(ErrorMessage.Delete);
throw err;
})
.finally(() => {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
inputRef.current?.focus();
});
};

const handleUpdateTodo = (
todoId: number,
data: Partial<Todo>,
): Promise<void> => {
setLoadingTodoIds(prev => [...prev, todoId]);
setErrorMessage(null);

return updateTodo(todoId, data)
.then(updatedTodo => {
setTodos(prev =>
prev.map(todo => (todo.id === todoId ? updatedTodo : todo)),
);
})
.catch(err => {
setErrorMessage(ErrorMessage.Update);
throw err;
})
.finally(() => {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
inputRef.current?.focus();
});
};

const handleToggleAll = () => {
const allCompleted = todos.every(t => t.completed);
const targetCompleted = !allCompleted;
const todosToUpdate = todos.filter(t => t.completed !== targetCompleted);

todosToUpdate.forEach(todo => {
handleUpdateTodo(todo.id, { completed: targetCompleted }).catch(() => {});
});
};

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

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

const visibleTodos = todos.filter(todo => {
if (filter === 'active') {
return !todo.completed;
}

if (filter === 'completed') {
return todo.completed;
}

return true;
});

const allCompleted = todos.length > 0 && todos.every(t => t.completed);
const activeTodosCount = todos.filter(t => !t.completed).length;
const completedTodosCount = todos.filter(t => t.completed).length;
const activeCountText = `${activeTodosCount} ${
activeTodosCount === 1 ? 'item' : 'items'
} left`;

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 className="todoapp__header">
{todos.length > 0 && (
<button
data-cy="ToggleAllButton"
type="button"
className={classNames('todoapp__toggle-all', {
active: allCompleted,
})}
onClick={handleToggleAll}
/>
)}

<form onSubmit={handleAddTodo}>
<input
data-cy="NewTodoField"
type="text"
ref={inputRef}
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={newTitle}
onChange={e => setNewTitle(e.target.value)}
disabled={isAdding}
/>
</form>
</header>

{(todos.length > 0 || tempTodo) && (
<>
<TodoList
todos={visibleTodos}
tempTodo={tempTodo}
loadingTodoIds={loadingTodoIds}
onDelete={handleDeleteTodo}
onUpdate={handleUpdateTodo}
/>

{todos.length > 0 && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeCountText}
</span>

<TodoFilter filter={filter} onChange={setFilter} />

<button
data-cy="ClearCompletedButton"
type="button"
className="todoapp__clear-completed"
disabled={completedTodosCount === 0}
onClick={handleClearCompleted}
>
Clear completed
</button>
</footer>
)}
</>
)}
</div>

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

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

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

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);
};
46 changes: 46 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React, { useEffect } from 'react';
import classNames from 'classnames';

import { ErrorMessage } from '../types/ErrorMessage';

interface Props {
message: ErrorMessage | null;
onClose: () => void;
}

export const ErrorNotification: React.FC<Props> = ({ message, onClose }) => {
useEffect(() => {
if (!message) {
return;
}

const timer = setTimeout(() => {
onClose();
}, 3000);

return () => {
clearTimeout(timer);
};
}, [message, onClose]);

return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{ hidden: !message },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>
{message}
</div>
);
};
Loading
Loading