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

final version #1563

Open
wants to merge 2 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
8 changes: 4 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
175 changes: 158 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,167 @@
/* 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 { UserWarning } from './UserWarning';

const USER_ID = 0;
import React, { useEffect, useState, useMemo } from 'react';
import { Todo } from './types/Todo';
import {
USER_ID,
addTodo,
deleteTodo,
getTodos,
updateTodo,
} from './api/todos';
import { ErrorStatus } from './types/ErrorStatus';
import { Status } from './types/Status';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { ErrorNotification } from './components/ErrorNotification';
import { TodoList } from './components/TodoList';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
const [todoList, setTodoList] = useState<Todo[]>([]);
const [error, setError] = useState<ErrorStatus>(ErrorStatus.Empty);
const [filter, setFilter] = useState<Status>(Status.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

useEffect(() => {
getTodos()
.then(setTodoList)
.catch(() => {
setError(ErrorStatus.UnableToLoad);
});
}, []);

const todosActiveNum = useMemo(
() => todoList.filter(todo => !todo.completed).length,
[todoList],
);

const todosCompletedNum = useMemo(
() => todoList.filter(todo => todo.completed).length,
[todoList],
);

const allTodosCompleted = useMemo(
() => todoList.length === todosCompletedNum,
[todoList],

Check warning on line 48 in src/App.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

React Hook useMemo has a missing dependency: 'todosCompletedNum'. Either include it or remove the dependency array
);
Comment on lines +46 to +49

Choose a reason for hiding this comment

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

React Hook useMemo has a missing dependency: 'todosCompletedNum'. Either include it or remove the dependency array

Actually you don't need to use useMemo here as it's a primitive value


const handleAddTodo = async (todoTitle: string) => {
setTempTodo({ id: 0, title: todoTitle, completed: false, userId: USER_ID });
try {
const newTodo = await addTodo({ title: todoTitle, completed: false });

setTodoList(prev => [...prev, newTodo]);
} catch (err) {
setError(ErrorStatus.UnableToAdd);
throw err;
} finally {
setTempTodo(null);
}
};

const handleRemoveTodo = async (todoId: number) => {
setLoadingTodoIds(prev => [...prev, todoId]);
try {
await deleteTodo(todoId);
setTodoList(prev => prev.filter(todo => todo.id !== todoId));
} catch (err) {
setError(ErrorStatus.UnableToDelete);
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
}
};

const handleClearCompleted = async () => {
const completedTodos = todoList.filter(todo => todo.completed);

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

const handleUpdatedTodo = async (todoToUpdate: Todo): Promise<void> => {
setLoadingTodoIds(prev => [...prev, todoToUpdate.id]);
try {
const updatedTodo = await updateTodo(todoToUpdate);

setTodoList(prev =>
prev.map(todoElem =>
todoElem.id === updatedTodo.id ? todoToUpdate : todoElem,
),
);
// eslint-disable-next-line @typescript-eslint/no-shadow
} catch (error) {
setError(ErrorStatus.UnableToUpdate);
throw error;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
};

const handleToggleAll = async () => {
if (todosActiveNum > 0) {
const activeTodos = todoList.filter(todo => !todo.completed);

activeTodos.forEach(todo => {
handleUpdatedTodo({ ...todo, completed: true });
});
} else {
todoList.forEach(todo => {
handleUpdatedTodo({ ...todo, completed: false });
});
}
};

const filteredTodoList = (): Todo[] => {
switch (filter) {
case Status.Active:
return todoList.filter(todo => !todo.completed);
case Status.Completed:
return todoList.filter(todo => todo.completed);
default:
return todoList;
}
};

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
onAddTodo={handleAddTodo}
setErrorMessage={setError}
todoLength={todoList.length}
todoList={todoList}
onToggleAll={handleToggleAll}
allTodosCompleted={allTodosCompleted}
/>

{(!!todoList.length || tempTodo) && (
<>
<TodoList
filteredTodoList={filteredTodoList()}
loadingTodoIds={loadingTodoIds}
tempTodo={tempTodo}
handleRemoveTodo={handleRemoveTodo}
handleUpdatedTodo={handleUpdatedTodo}
/>

<Footer
todosCounter={todosActiveNum}
filterStatus={filter}
setFilter={setFilter}
onClearCompleted={handleClearCompleted}
showClearCompletedButton={todoList.some(todo => todo.completed)}
/>
</>
)}
</div>

<ErrorNotification error={error} setError={setError} />
</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 = 2138;

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

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

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

export const updateTodo = (todo: Todo) => {
return client.patch<Todo>(`/todos/${todo.id}`, todo);
};
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 { ErrorStatus } from '../types/ErrorStatus';
import cn from 'classnames';

type Props = {
error: string;
setError: React.Dispatch<React.SetStateAction<ErrorStatus>>;
};

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

useEffect(() => {
if (error === ErrorStatus.Empty) {
return;
}

const timerId = setTimeout(() => {
setError(ErrorStatus.Empty);
}, 3000);

return () => {
clearInterval(timerId);
};
}, [error, setError]);

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={() => setError(ErrorStatus.Empty)}
/>
{error}
</div>
);
};
55 changes: 55 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React from 'react';
import { Status } from '../types/Status';
import cn from 'classnames';

interface Props {
filterStatus: Status;
setFilter: (value: Status) => void;
todosCounter: number;
onClearCompleted: () => Promise<void>;
showClearCompletedButton: boolean;
}

export const Footer: React.FC<Props> = props => {
const {
setFilter,
filterStatus,
todosCounter,
onClearCompleted,
showClearCompletedButton,
} = props;

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

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

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompleted}
disabled={!showClearCompletedButton}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading