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 8 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
183 changes: 168 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,179 @@
/* 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 [loadingTodos, setLoadingTodos] = useState<number[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorMessage>(

Choose a reason for hiding this comment

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

Suggested change
const [loadingTodos, setLoadingTodos] = useState<number[]>([]);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);

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) => {
setLoadingTodos(prevTodos => [...prevTodos, todoToUpdate.id]);

return clientTodo
.updateTodo(todoToUpdate)
.then(updatedTodo => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(todo => todo.id === updatedTodo.id);

newTodos.splice(index, 1, updatedTodo);

return newTodos;
});

Choose a reason for hiding this comment

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

Use map instead

currentTodos.map(todo => todo.id === updatedTodo.id ? updatedTodo : todo)

})
.catch(err => {
setErrorMessage(ErrorMessage.UnableToUpdate);
throw err;
})
.finally(() => {
setLoadingTodos(prevTodos =>
prevTodos.filter(id => todoToUpdate.id !== id),
);
});
};

const onDeleteTodo = (todoId: number) => {
setLoadingTodos(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(() =>
setLoadingTodos(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}
/>

<TodoList
tempTodo={tempTodo}
filteredTodos={filteredTodos}
loadingTodos={loadingTodos}
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]);

Check warning on line 23 in src/components/ErrorNotification.tsx

View workflow job for this annotation

GitHub Actions / run_linter (20.x)

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

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