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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
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
5,182 changes: 3,032 additions & 2,150 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
178 changes: 163 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,174 @@
/* 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, useMemo, useState } from 'react';
import { UserWarning } from './UserWarning';
import * as clientTodo from './api/todos';
import { getFilteredTodos } from './utils/getFilteredTodos';

const USER_ID = 0;
import { ErrorMessage } from './types/ErrorMessage';
import { Todo } from './types/Todo';
import { Status } from './types/Status';

import { TodoHeader } from './components/TodoHeader';
import { TodoFooter } from './components/TodoFooter';
import { ErrorNotification } from './components/ErrorNotification';
import { TodoList } from './components/TodoList';

export const App: React.FC = () => {
if (!USER_ID) {
const [todos, setTodos] = useState<Todo[]>([]);
const [activeStatus, setActiveStatus] = useState(Status.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorMessage>(
ErrorMessage.Default,
);

const filteredTodos = useMemo(
() => getFilteredTodos(todos, activeStatus),
[todos, activeStatus],
);
const notCompletedTodos = useMemo(
() => todos.filter(todo => !todo.completed),
[todos],
);
const completedTodos = useMemo(
() => todos.filter(todo => todo.completed),
[todos],
);
const isToogleAll = completedTodos.length === todos.length;

const onAddTodo = (title: string) => {
setTempTodo({
id: 0,
title,
userId: clientTodo.USER_ID,
completed: false,
});

const newTodo: Omit<Todo, 'id'> = {
title,
userId: clientTodo.USER_ID,
completed: false,
};

return clientTodo
.createTodos(newTodo)
.then(todo => setTodos(currentTodos => [...currentTodos, todo]))
.catch(err => {
setErrorMessage(ErrorMessage.UnableToAdd);
throw err;
})
.finally(() => setTempTodo(null));
};

const onUpdateTodo = (todoToUpdate: Todo) => {
setLoadingTodoIds(prevTodos => [...prevTodos, todoToUpdate.id]);

return clientTodo
.updateTodo(todoToUpdate)
.then(updatedTodo => {
setTodos(currentTodos => {
return currentTodos.map(todo =>
todo.id === updatedTodo.id ? updatedTodo : todo,
);
});
})
.catch(err => {
setErrorMessage(ErrorMessage.UnableToUpdate);
throw err;
})
.finally(() => {
setLoadingTodoIds(prevTodos =>
prevTodos.filter(id => todoToUpdate.id !== id),
);
});
};

const onDeleteTodo = (todoId: number) => {
setLoadingTodoIds(prevTodos => [...prevTodos, todoId]);

clientTodo
.deleteTodo(todoId)
.then(() =>
setTodos(currentTodos =>
currentTodos.filter(todo => todo.id !== todoId),
),
)
.catch(() => {
setErrorMessage(ErrorMessage.UnableToDelete);
})
.finally(() =>
setLoadingTodoIds(prevTodos => prevTodos.filter(id => todoId !== id)),
);
};

const onDeleteAllCompleted = () => {
completedTodos.forEach(todo => onDeleteTodo(todo.id));
};

const onToggleAll = () => {
if (todos.every(todo => todo.completed)) {
todos.forEach(todo => onUpdateTodo({ ...todo, completed: false }));
} else {
todos.filter(todo => {
if (!todo.completed) {
onUpdateTodo({ ...todo, completed: true });
}
});
}
};

useEffect(() => {
clientTodo
.getTodos()
.then(data => setTodos(data))
.catch(() => {
setErrorMessage(ErrorMessage.UnableToLoad);
});
}, []);

if (!clientTodo.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
error={errorMessage}
isToogleAll={todos.length === 0 ? null : isToogleAll}
isInputDisablet={!!tempTodo}
isDeletedTodos={todos.length}
onAddTodo={onAddTodo}
onToggleAll={onToggleAll}
setErrorMessage={setErrorMessage}
/>

<TodoList
tempTodo={tempTodo}
filteredTodos={filteredTodos}
loadingTodoIds={loadingTodoIds}
onDeleteTodo={onDeleteTodo}
onUpdateTodo={onUpdateTodo}
/>

{!!todos.length && (
<TodoFooter
activeStatus={activeStatus}
completedTodos={completedTodos.length}
notCompletedTodos={notCompletedTodos.length}
onDeleteAllCompleted={onDeleteAllCompleted}
setActiveStatus={setActiveStatus}
/>
)}
</div>

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

export const USER_ID = 2135;

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

Choose a reason for hiding this comment

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

let's move /todos into const and reuse

};

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

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

export const updateTodo = ({ id, title, completed, userId }: Todo) => {
return client.patch<Todo>(`/todos/${id}`, { title, completed, userId });
};
44 changes: 44 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React, { useEffect } from 'react';
import cn from 'classnames';
import { ErrorMessage } from '../types/ErrorMessage';

type Props = {
error: string;
setErrorMessage: (error: ErrorMessage) => void;
};

export const ErrorNotification: React.FC<Props> = props => {
const { error, setErrorMessage } = props;

useEffect(() => {
if (error === ErrorMessage.Default) {
return;
}

const timer = setTimeout(() => {
setErrorMessage(ErrorMessage.Default);
}, 3000);

return () => clearTimeout(timer);
}, [error, setErrorMessage]);

return (
<div
data-cy="ErrorNotification"
className={cn(
'notification',
'is-danger',
'is-light has-text-weight-normal',
{ hidden: !error },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage}
/>
{error}
</div>
);
};
56 changes: 56 additions & 0 deletions src/components/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable prettier/prettier */
import React from 'react';
import cn from 'classnames';
import { Status } from '../types/Status';

type Props = {
activeStatus: Status;
completedTodos: number;
notCompletedTodos: number;
onDeleteAllCompleted: () => void;
setActiveStatus: (status: Status) => void;
};

export const TodoFooter: React.FC<Props> = props => {
const {
activeStatus,
completedTodos,
notCompletedTodos,
onDeleteAllCompleted,
setActiveStatus,
} = props;

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{notCompletedTodos} items left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(Status).map(status => (
<a
key={status}
data-cy={`FilterLink${status}`}
href={status === 'All' ? '#/' : `#/${status.toLowerCase()}`}

Choose a reason for hiding this comment

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

Suggested change
href={status === 'All' ? '#/' : `#/${status.toLowerCase()}`}
href={status === Enum ? '#/' : `#/${status.toLowerCase()}`}

let's use enum

className={cn('filter__link', {
selected: activeStatus === status,
})}
onClick={() => setActiveStatus(status)}
>
{status}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={completedTodos === 0}
onClick={onDeleteAllCompleted}
>
Clear completed
</button>
</footer>
);
};
76 changes: 76 additions & 0 deletions src/components/TodoHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React, { useEffect, useRef, useState } from 'react';
import cn from 'classnames';
import { ErrorMessage } from '../types/ErrorMessage';

type Props = {
error: ErrorMessage;
isToogleAll: boolean | null;

Choose a reason for hiding this comment

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

In what case should it be null? it's a bit confusing

Copy link
Author

Choose a reason for hiding this comment

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

in this case boolean defines 'active' button or not, but null defines is the button in the input at all or not

isInputDisablet: boolean;
isDeletedTodos: number;
onAddTodo: (title: string) => Promise<void>;
onToggleAll: () => void;
setErrorMessage: (error: ErrorMessage) => void;
};

export const TodoHeader: React.FC<Props> = props => {
const {
error,
isToogleAll,
isInputDisablet,
isDeletedTodos,
onAddTodo,
onToggleAll,
setErrorMessage,
} = props;

const [title, setTitle] = useState('');
const inputRef = useRef<HTMLInputElement | null>(null);

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

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

if (error !== ErrorMessage.Default) {
setErrorMessage(ErrorMessage.Default);
}

if (!title.trim()) {
setErrorMessage(ErrorMessage.EmptyTitle);

return;
}

onAddTodo(title.trim()).then(() => setTitle(''));
};

return (
<header className="todoapp__header">
{isToogleAll !== null && (

Choose a reason for hiding this comment

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

Suggested change
{isToogleAll !== null && (
{isToogleAll && (

<button
type="button"
className={cn('todoapp__toggle-all', { active: isToogleAll })}
data-cy="ToggleAllButton"
onClick={onToggleAll}
/>
)}

<form onSubmit={handleSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
ref={inputRef}
value={title}
onChange={event => setTitle(event.target.value)}
disabled={isInputDisablet}
/>
</form>
</header>
);
};
Loading
Loading