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

done #1575

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

done #1575

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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ Implement the ability to edit a todo title on double click:

- Implement a solution following the [React task guideline](https://github.com/mate-academy/react_task-guideline#react-tasks-guideline).
- Use the [React TypeScript cheat sheet](https://mate-academy.github.io/fe-program/js/extra/react-typescript).
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://<your_account>.github.io/react_todo-app-with-api/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://AlexLiashenko19.github.io/react_todo-app-with-api/) and add it to the PR description.
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
203 changes: 184 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,191 @@
/* 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, useMemo, useRef, useState } from 'react';
import { Todo } from './types/Todo';
import * as todoService from './api/todos';
import { Error } from './components/Error';
import { TodoList } from './components/TodoList';
import { FilterStatus } from './types/FilterTypes';
import { ErrorType } from './types/ErrorTypes';
import { Footer } from './components/Footer';
import { Header } from './components/Header';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
// #region state
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorType>(ErrorType.Empty);
const [filterStatus, setFilterStatus] = useState<FilterStatus>(
FilterStatus.All,
);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

const inputAddRef = useRef<HTMLInputElement>(null);
// #endregionstate

// #region lifecycle
const filteredTodos = useMemo(
() =>
todos.filter(todo => {
if (filterStatus === FilterStatus.All) {
return true;
}

return filterStatus === FilterStatus.Completed
? todo.completed
: !todo.completed;
}),
[todos, filterStatus],
);

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

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

const todosCompleted = useMemo(
() => todos.filter(todo => todo.completed).length,
[todos],
);

const areAllTodosCompleted = useMemo(
() => todos.every(todo => todo.completed),
[todos],
);

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

setTodos(prev => [...prev, newTodo]);
} catch (err) {
setErrorMessage(ErrorType.AddTodo);
inputAddRef?.current?.focus();
throw err;
} finally {
setTempTodo(null);
}
};

const onRemoveTodo = async (todoId: number) => {
setLoadingTodoIds(prev => [...prev, todoId]);
try {
await todoService.deleteTodo(todoId);

setTodos(prev => prev.filter(todo => todo.id !== todoId));
} catch (err) {
setErrorMessage(ErrorType.DeleteTodo);
inputAddRef?.current?.focus();
throw err;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoId));
}
};

const onClearCompleted = async () => {
const completedTodos = todos.filter(todo => todo.completed);

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

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

setTodos(prev =>
prev.map(todo => (todo.id === updateTodo.id ? updateTodo : todo)),
);
} catch (err) {
setErrorMessage(ErrorType.UpdateTodo);
throw err;
} finally {
setLoadingTodoIds(prev => prev.filter(id => id !== todoToUpdate.id));
}
};

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

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

useEffect(() => {
(async () => {
try {
const data = await todoService.getTodos();

setTodos(data);
} catch (err) {
setErrorMessage(ErrorType.LoadTodos);
}
})();
}, []);

// #endregionlife

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={addTodo}
setErrorMessage={setErrorMessage}
isInputDisabled={!!tempTodo}
todosLength={todos.length}
inputRef={inputAddRef}
onToggleAll={toggleTodo}
areAllTodosCompleted={areAllTodosCompleted}
/>

{(todos.length > 0 || tempTodo) && (
<>
<TodoList
todos={filteredTodos}
onRemoveTodo={onRemoveTodo}
loadingTodoIds={loadingTodoIds}
updatedTodo={updatedTodo}
tempTodo={tempTodo}
/>
<Footer
filterStatus={filterStatus}
setFilterStatus={setFilterStatus}
todosLeft={todosLeftNum}
todosCompleted={todosCompleted}
onClearCompleted={onClearCompleted}
/>
</>
)}

{/* Hide the footer if there are no todos */}
</div>

<Error error={errorMessage} setError={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}`);
};

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

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

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

type Props = {
error: ErrorType;
setError: Dispatch<SetStateAction<ErrorType>>;
};

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

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

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

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

return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: error === ErrorType.Empty },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setError(ErrorType.Empty)}
/>
{error}
</div>
);
};
57 changes: 57 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React, { Dispatch, SetStateAction } from 'react';
import classNames from 'classnames';
import { FilterStatus } from '../types/FilterTypes';

type Props = {
filterStatus: FilterStatus;
setFilterStatus: Dispatch<SetStateAction<FilterStatus>>;
todosLeft: number;
todosCompleted: number;
onClearCompleted: () => Promise<void>;
};

export const Footer: React.FC<Props> = props => {
const {
filterStatus,
setFilterStatus,
todosLeft,
todosCompleted,
onClearCompleted,
} = props;

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

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
{Object.values(FilterStatus).map(filter => (
<a
key={filter}
href={`#/${filter === FilterStatus.All ? '' : filter.toLocaleLowerCase()}`}
className={classNames('filter__link', {
selected: filterStatus === filter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => setFilterStatus(filter)}
>
{filter}
</a>
))}
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompleted}
disabled={todosCompleted === 0}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading