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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
293 changes: 185 additions & 108 deletions package-lock.json

Large diffs are not rendered by default.

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": "^1.9.12",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
318 changes: 303 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,314 @@
/* eslint-disable max-len */
/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { UserWarning } from './UserWarning';
import {
getTodos,
USER_ID,
deleteTodo,
addTodo,
updateTodo,
} from './api/todos';
import { Todo } from './types/Todo';
import { Error } from './types/enumError';
import { FilterName } from './types/enumFilterName';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { ErrorMes } from './components/ErrorMes';

const USER_ID = 0;
export const App = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<Error>(Error.Default);
const [filteredBy, setFilteredBy] = useState<FilterName>(FilterName.ALL);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [newTodoTitle, setNewTodoTitle] = useState('');
const [loadingTodoId, setLoadingTodoId] = useState<number | null>(null);
const [isInputDisabled, setIsInputDisabled] = useState(false);
const [editingTodoId, setEditingTodoId] = useState<number | null>(null);
const [editingTitle, setEditingTitle] = useState<string>('');

Krrampuss marked this conversation as resolved.
Show resolved Hide resolved
Krrampuss marked this conversation as resolved.
Show resolved Hide resolved
const activeCount = todos.filter(todo => !todo.completed).length;
const completedTodos = todos.filter(todo => todo.completed);

Krrampuss marked this conversation as resolved.
Show resolved Hide resolved
const inputRef = useRef<HTMLInputElement>(null);

function loadTodos() {
getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage(Error.Load);
setTimeout(() => setErrorMessage(Error.Default), 3000);
});
}

useEffect(() => {
loadTodos();
}, []);

useEffect(() => {
if (!isInputDisabled && inputRef.current) {
inputRef.current.focus();
}
}, [isInputDisabled]);

Krrampuss marked this conversation as resolved.
Show resolved Hide resolved
const filteredTodos = useMemo(() => {
switch (filteredBy) {
case FilterName.ACTIVE:
return todos.filter(todo => !todo.completed);
case FilterName.COMPLETED:
return todos.filter(todo => todo.completed);
default:
return todos;
}
}, [todos, filteredBy]);

function addPost(loadingTodo: Todo) {
setTempTodo(loadingTodo);
setErrorMessage(Error.Default);
setIsInputDisabled(true);

addTodo({
userId: loadingTodo.userId,
title: loadingTodo.title,
completed: loadingTodo.completed,
})
.then(createdTodo => {
setTodos(currentTodos => [...currentTodos, createdTodo]);
setNewTodoTitle('');
})
.catch(() => {
setErrorMessage(Error.Add);
setTimeout(() => setErrorMessage(Error.Default), 3000);
})
.finally(() => {
setTempTodo(null);
setIsInputDisabled(false);
inputRef.current?.focus();
});
}

function handleSubmit(event: React.FormEvent) {
event.preventDefault();

const trimmedTitle = newTodoTitle.trim();

if (!trimmedTitle) {
setErrorMessage(Error.Empty);
setTimeout(() => setErrorMessage(Error.Default), 3000);

return;
}

const loadingTodo: Todo = {
userId: USER_ID,
title: trimmedTitle,
completed: false,
id: 0,
};

setTempTodo(loadingTodo);
addPost(loadingTodo);
}

const deletePost = useCallback((todoId: number) => {
setLoadingTodoId(todoId);
deleteTodo(todoId)
.then(() => {
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
);
})
.catch(() => {
setErrorMessage(Error.Delete);
setTimeout(() => setErrorMessage(Error.Default), 3000);
})
.finally(() => {
setLoadingTodoId(null);
inputRef.current?.focus();
});
}, []);

const deleteCompleted = useCallback(() => {
const completedIds = todos
.filter(todo => todo.completed)
.map(todo => todo.id);

completedIds.forEach(id => deletePost(id));
}, [todos, deletePost]);

function togglCompleted(todoId: number) {
const currentTodo = todos.find(todo => todo.id === todoId);
Krrampuss marked this conversation as resolved.
Show resolved Hide resolved

if (!currentTodo) {
return;
}

const newCompletionState = !currentTodo.completed;

setLoadingTodoId(todoId);

updateTodo(todoId, newCompletionState, currentTodo.title)
.then(() => {
setTodos(prevTodos =>
prevTodos.map(todo =>
todo.id === todoId
? { ...todo, completed: newCompletionState }
: todo,
),
);
})
.catch(() => {
setErrorMessage(Error.Update);
setTimeout(() => setErrorMessage(Error.Default), 3000);
})
.finally(() => {
setLoadingTodoId(null);
});
}

async function completeAll() {
const allCompleted = todos.every(todo => todo.completed);
const newCompletionState = !allCompleted;

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

const failedIds: number[] = [];

for (const todo of todosToUpdate) {
try {
await updateTodo(todo.id, newCompletionState, todo.title);
} catch {
failedIds.push(todo.id);
}
}

Krrampuss marked this conversation as resolved.
Show resolved Hide resolved
setTodos(currentTodos =>
currentTodos.map(todo =>
failedIds.includes(todo.id)
? todo
: { ...todo, completed: newCompletionState },
),
);

if (failedIds.length > 0) {
setErrorMessage(Error.Update);
}
}

const updateTitle = useCallback(
(todoId: number) => {
const trimmedTitle = editingTitle.trim();
const currentTodo = todos.find(todo => todo.id === todoId);

if (currentTodo && trimmedTitle === currentTodo.title) {
setEditingTodoId(null);

return;
}

if (trimmedTitle === '') {
deletePost(todoId);
Krrampuss marked this conversation as resolved.
Show resolved Hide resolved
} else {
setLoadingTodoId(todoId);

updateTodo(todoId, currentTodo?.completed || false, trimmedTitle)
.then(() => {
setTodos(prevTodos =>
prevTodos.map(todo =>
todo.id === todoId ? { ...todo, title: trimmedTitle } : todo,
),
);
setEditingTodoId(null);
})
.catch(() => {
setErrorMessage(Error.Update);
setTimeout(() => setErrorMessage(Error.Default), 3000);
})
.finally(() => {
setLoadingTodoId(null);
});
}
},
[todos, editingTitle, deletePost],
);

useEffect(() => {
if (errorMessage) {
const timer = setTimeout(() => setErrorMessage(Error.Default), 3000);

return () => clearTimeout(timer);
}

return;
}, [errorMessage]);
Krrampuss marked this conversation as resolved.
Show resolved Hide resolved

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}

const handleCancelEdit = useCallback(() => {
setEditingTodoId(null);
setEditingTitle('');
}, []);

const handleEditTodo = useCallback((todoId: number, title: string) => {
setEditingTodoId(todoId);
setEditingTitle(title);
}, []);

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}
completeAll={completeAll}
activeCount={activeCount}
handleSubmit={handleSubmit}
inputRef={inputRef}
newTodoTitle={newTodoTitle}
setNewTodoTitle={setNewTodoTitle}
isInputDisabled={isInputDisabled}
/>
{!!todos.length && (
<TodoList
filteredTodos={filteredTodos}
togglCompleted={togglCompleted}
editingTodoId={editingTodoId}
editingTitle={editingTitle}
setEditingTitle={setEditingTitle}
updateTitle={updateTitle}
handleCancelEdit={handleCancelEdit}
handleEditTodo={handleEditTodo}
loadingTodoId={loadingTodoId}
deletePost={deletePost}
tempTodo={tempTodo}
/>
)}

{!!todos.length && (
<Footer
activeCount={activeCount}
filteredBy={filteredBy}
setFilteredBy={setFilteredBy}
deleteCompleted={deleteCompleted}
completedTodos={completedTodos}
/>
)}
</div>

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

export const USER_ID = 2129;

export const getTodos = () => {
const baseUrl = `/todos?userId=${USER_ID}`;
Krrampuss marked this conversation as resolved.
Show resolved Hide resolved

return client.get<Todo[]>(baseUrl);
};

export const deleteTodo = (id: number) => {
const baseUrl = `/todos/${id}`;

return client.delete(baseUrl);
};

export const addTodo = (newTodo: Omit<Todo, 'id'>) => {
const baseUrl = `/todos`;

return client.post<Todo>(baseUrl, newTodo);
};

export const updateTodo = (id: number, completed: boolean, title?: string) => {
const baseUrl = `/todos/${id}`;

const updateData: { completed: boolean; title?: string } = { completed };

if (title) {
updateData.title = title;
}

return client.patch(baseUrl, updateData);
};
19 changes: 19 additions & 0 deletions src/components/ErrorMes.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
type Props = {
errorMessage: string;
};

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