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

Develop #1534

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Develop #1534

Show file tree
Hide file tree
Changes from 4 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": "^1.9.12",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
291 changes: 277 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,289 @@
/* 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, { useState, useEffect } from 'react';

import { UserWarning } from './UserWarning';
import { USER_ID } from './api/todos';
import { Header } from './components/Header/Header';
import { TodoList } from './components/TodoList/TodoList';
import { TempTodo } from './components/TempTodo/TempTodo';
import { Footer } from './components/Footer/Fotter';
import { Error } from './components/Error/Erros';
import { getTodos, addTodo, deleteTodo, updateTodo } from './api/todos';

import { Todo } from './types/Todo';
import { TodoStatus } from './types/Status';

const USER_ID = 0;
function filterTodos(todos: Todo[], status: TodoStatus) {
const todosCopy = [...todos];

switch (status) {
case TodoStatus.active:
return todosCopy.filter(todo => !todo.completed);
case TodoStatus.completed:
return todosCopy.filter(todo => todo.completed);
case TodoStatus.all:
return todosCopy;
}
}

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState('');
const [status, setStatus] = useState<TodoStatus>(TodoStatus.all);
const [title, setTitle] = useState('');
const [loading, setLoading] = useState(false);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [processedIs, setProcessedIs] = useState<number[]>([]);
const areAllTodosCompleted = todos.every(todo => todo.completed);
const noTodos = todos.length === 0;
const filteredTodos = filterTodos(todos, status);

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

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not forget about useCallback and useMemo for functions and values


const normalizeTitle = title.trim();

if (!normalizeTitle) {
setErrorMessage('Title should not be empty');

return;
}

setLoading(true);
const newTodo = {
userId: 2042,
title: normalizeTitle,
completed: false,
};

setTempTodo({
id: 0,
...newTodo,
});

addTodo(newTodo)
.then(response => {
setTitle('');
setTodos(existing => [...existing, response]);
setLoading(false);
})
.catch(() => setErrorMessage('Unable to add a todo'))
.finally(() => {
setLoading(false);
setTempTodo(null);
});
};

const handleDeleteOneTodo = (id: number) => {
setLoading(true);
setProcessedIs(existing => [...existing, id]);
deleteTodo(id)
.then(() => {
setTodos(existing => existing.filter(current => current.id !== id));
})
.catch(() => setErrorMessage('Unable to delete a todo'))
.finally(() => {
setProcessedIs([]);
setLoading(false);
});
};

const handleDeleteCompletedTodos = () => {
todos.forEach(todo => {
if (todo.completed) {
setLoading(true);
setProcessedIs(existing => [...existing, todo.id]);
deleteTodo(todo.id)
.then(() =>
setTodos(existing =>
existing.filter(current => current.id !== todo.id),
),
)
.catch(() => setErrorMessage('Unable to delete a todo'))
.finally(() => {
setLoading(false);
setProcessedIs(existing => existing.filter(id => id !== todo.id));
});
}
});
};

const handleStatusUpdate = (id: number) => {
setProcessedIs(existing => [...existing, id]);

const changeItem = todos.find(todo => todo.id === id);

if (changeItem) {
const toUpdate = { completed: !changeItem.completed };

updateTodo(id, toUpdate)
.then(() => {
setTodos(existing =>
existing.map(el =>
el.id === id ? { ...el, completed: toUpdate.completed } : el,
),
);
})
.catch(() => setErrorMessage('Unable to update a todo'))
.finally(() => {
setProcessedIs([]);
});
}
};

const handleTotalStatusUpdate = () => {
if (!areAllTodosCompleted) {
todos.forEach(todo => {
if (!todo.completed) {
setLoading(true);
setProcessedIs(existing => [...existing, todo.id]);
const toUpdate = { completed: true };

updateTodo(todo.id, toUpdate)
.then(() => {
setTodos(existing =>
existing.map(el =>
el.id === todo.id
? { ...el, completed: toUpdate.completed }
: el,
),
);
})
.catch(() => setErrorMessage('Unable to update a todo'))
.finally(() => {
setLoading(false);
setProcessedIs(existing => existing.filter(id => id !== todo.id));
});
}
});
}

if (areAllTodosCompleted) {
todos.forEach(todo => {
setLoading(true);
setProcessedIs(existing => [...existing, todo.id]);
const toUpdate = { completed: false };

updateTodo(todo.id, toUpdate)
.then(() => {
setTodos(existing =>
existing.map(el =>
el.id === todo.id
? { ...el, completed: toUpdate.completed }
: el,
),
);
})
.catch(() => setErrorMessage('Unable to update a todo'))
.finally(() => {
setLoading(false);
setProcessedIs(existing => existing.filter(id => id !== todo.id));
});
});
}
};

const handleTitleUpdate = (
id: number,
newTitle: string,
setTitleBeingUpdated: React.Dispatch<React.SetStateAction<boolean>>,
isTitleChanged: boolean,
e?: React.FormEvent<HTMLFormElement>,
) => {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do not pass it as an arguments

Instead, in TodoItem component create a separate function handler onSubmit. In this function, you should apply local logic (event.preventDefault, input focus, etc.) and just call this function with todo id and new title

Apply the same approach for other functions as well

e?.preventDefault();

const normalizeNewTitle = newTitle.trim();

if (!normalizeNewTitle) {
handleDeleteOneTodo(id);

return;
}

if (!isTitleChanged) {
setTitleBeingUpdated(false);

return;
}

const changeItem = todos.find(todo => todo.id === id);
const toUpdate = { title: normalizeNewTitle };

if (changeItem) {
setProcessedIs(existing => [...existing, id]);
updateTodo(id, toUpdate)
.then(() => {
setTodos(existing =>
existing.map(el =>
el.id === id ? { ...el, title: toUpdate.title } : el,
),
);
setTitleBeingUpdated(false);
})
.catch(() => setErrorMessage('Unable to update a todo'))
.finally(() => {
setProcessedIs([]);
});
}
};

const handleKeyUp = (
event: React.KeyboardEvent<HTMLInputElement>,
setTitleBeingUpdated: React.Dispatch<React.SetStateAction<boolean>>,
) => {
if (event.key === 'Escape') {
setTitleBeingUpdated(false);
}
};

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
allTodosCompleted={areAllTodosCompleted}
noTodos={noTodos}
onSubmit={handleSubmit}
loading={loading}
title={title}
onTitleChange={value => setTitle(value)}
onTotalStatusUpdate={handleTotalStatusUpdate}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
onTitleChange={value => setTitle(value)}
onTitleChange={setTitle}

/>

<TodoList
filteredTodos={filteredTodos}
onDelete={handleDeleteOneTodo}
onStatusUpdate={handleStatusUpdate}
onUpdatedTitleSubmit={handleTitleUpdate}
onKeyUp={handleKeyUp}
processedIs={processedIs}
/>

{tempTodo && <TempTodo todo={tempTodo} />}

{!noTodos && (
<Footer
todos={todos}
status={status}
onStatusChange={(value: TodoStatus) => setStatus(value)}
clearCompletedTodos={handleDeleteCompletedTodos}
/>
)}
</div>

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

export const USER_ID = 2042;

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

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

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

export const updateTodo = (todoId: number, todoData: Partial<Todo>) => {
return client.patch(`/todos/${todoId}`, todoData);
};

// Add more methods here
34 changes: 34 additions & 0 deletions src/components/Error/Erros.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React, { useEffect } from 'react';
import classNames from 'classnames';

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

export const Error: React.FC<Props> = ({ errorMessage, hideError }) => {
useEffect(() => {
setTimeout(() => hideError(''), 3000);
});

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={() => hideError('')}
/>
{errorMessage}
</div>
);
};
Empty file added src/components/Error/index.tsx
Empty file.
Loading
Loading