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 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
196 changes: 181 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,192 @@
/* 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 { TodoItem } from './components/TodoItem';
import { ErrorNotification } from './components/ErrorNotification';

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 [isLoadingTodos, setIsLoadingTodos] = 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 = async (title: string) => {
setTempTodo({
id: 0,
title,
userId: clientTodo.USER_ID,
completed: false,
});

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

try {
const todo = await clientTodo.createTodos(newTodo);

setTodos(currentTodos => [...currentTodos, todo]);
} catch (error) {
setErrorMessage(ErrorMessage.UnableToAdd);
throw error;
} finally {
setTempTodo(null);
}
};

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

try {
const updatedTodo = await clientTodo.updateTodo(todoToUpdate);

setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(todo => todo.id === updatedTodo.id);

newTodos.splice(index, 1, updatedTodo);

return newTodos;
});
} catch (error) {
setErrorMessage(ErrorMessage.UnableToUpdate);

throw error;
} finally {
setIsLoadingTodos(prevTodos =>
prevTodos.filter(id => todoToUpdate.id !== id),
);
}
};

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

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

Choose a reason for hiding this comment

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

You don't need to throw an error if you don't handle it on the next step. Fix in all places

.finally(() =>
setIsLoadingTodos(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(error => {
setErrorMessage(ErrorMessage.UnableToLoad);
throw error;
});
}, []);

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}
/>

<section className="todoapp__main" data-cy="TodoList">
{filteredTodos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onDeleteTodo={onDeleteTodo}
onUpdateTodo={onUpdateTodo}
isLoading={isLoadingTodos.includes(todo.id)}
/>
))}
{tempTodo && (
<TodoItem
todo={tempTodo}
onDeleteTodo={onDeleteTodo}
onUpdateTodo={onUpdateTodo}
isLoading={isLoadingTodos.includes(tempTodo.id)}
/>
)}
</section>

{!!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 });
};
45 changes: 45 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [error]);

Choose a reason for hiding this comment

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

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


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>
);
};
Loading
Loading