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

Open
wants to merge 3 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,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://antonina-klishch.github.io/react_todo-app-with-api/) and add it to the PR description.
293 changes: 280 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,291 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState } from 'react';
import cn from 'classnames';
import * as todoService from './api/todos';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { TodoList } from './components/TodoList';
import { Todo } from './types/Todo';
import { getTodos } from './api/todos';
import { USER_ID } from './utils/fetchClient';
import { Status } from './types/Status';
import { Message } from './types/Message';
import { ErrorNotification } from './components/ErrorNotification';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [todosStatus, setTodosStatus] = useState<Status>(Status.All);
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<Message | ''>('');
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [titleTodo, setTitleTodo] = useState('');
const [deletedTodo, setDeletedTodo] = useState<number[] | null>(null);
const [changedTodo, setChangedTodo] = useState<number[] | null>(null);

const filterTodos = (listTodos: Todo[], status: Status) => {
switch (status) {
case Status.Active:
return listTodos.filter(todo => !todo.completed);
case Status.Completed:
return listTodos.filter(todo => todo.completed);
case Status.All:
default:
return listTodos;
}
};

const addTodo = ({ userId, title, completed }: Todo) => {
setErrorMessage('');
setIsLoading(true);

const createdTodo = {
id: 0,
userId: USER_ID,
title: title.trim(),
completed: false,
};

setTempTodo(createdTodo);

todoService.createTodo({ userId, title, completed })
.then(newTodo => {
setTodos(currentTodos => [...currentTodos, newTodo]);
setTitleTodo('');
})
.catch(() => {
setErrorMessage(Message.NoAddTodo);
})
.finally(() => {
setIsLoading(false);
setTempTodo(null);
});
};

const removeComplatedTodos = (todosId: number[] | null) => {
setIsLoading(true);

Choose a reason for hiding this comment

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

Suggested change
const removeComplatedTodos = (todosId: number[] | null) => {
const removeCompletedTodos = (todosId: number[] | null) => {


if (todosId) {
setDeletedTodo(todosId);
todosId.map(todoId => {
return todoService.deleteTodos(todoId)
.then(() => {
setTodos(currentTodos => (
currentTodos.filter(todo => todo.id !== todoId)
));
})
.catch((error) => {
setDeletedTodo(null);
setErrorMessage(Message.NoDeleteTodo);
throw error;
})
.finally(() => {
setIsLoading(false);
setDeletedTodo(null);
});
});
}
};

Choose a reason for hiding this comment

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

set loading to false after this if block by default

Choose a reason for hiding this comment

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

by the way, why you need this if? you can trigger this function only if todosId array is not empty


const updateTodoStatus = (updatedTodo: Todo) => {
setErrorMessage('');
setIsLoading(true);
setChangedTodo([updatedTodo.id]);

return todoService.updateTodo(updatedTodo)
.then(() => {
setTodos(todos.map(todo => (
todo.id === updatedTodo.id
? {
...todo,
completed: updatedTodo.completed,

}
: todo
)));
})

.catch(() => setErrorMessage(Message.NoUpdateTodo))
.finally(() => {
setIsLoading(false);
setChangedTodo(null);
});
};

const updateTodosAllStatus = (updatedTodos: Todo[]) => {
setErrorMessage('');
setIsLoading(true);
const changedTodoId: number[] = [];

Choose a reason for hiding this comment

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

pay attention to naming please

Suggested change
const changedTodoId: number[] = [];
const changedTodoIds: number[] = [];

updatedTodos.forEach(updatedTodo => {
const similarTodo = todos.find(todo => todo.id === updatedTodo.id);

if (similarTodo && similarTodo.completed !== updatedTodo.completed) {
changedTodoId.push(similarTodo.id);
}
});

setChangedTodo(changedTodoId);

const updatedTodoSirvice = updatedTodos.map(async (todo) => {
try {

Choose a reason for hiding this comment

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

what is Sirvice?

const todoChange = await todoService.updateTodo(todo);

return todoChange;
} catch (error) {
setErrorMessage(Message.NoUpdateTodo);

return todo;
}
});

Promise.all(updatedTodoSirvice)
.then((gettedTodos) => {
const gettedTodosId = gettedTodos.map(t => t.id);

setTodos(curT => curT.map(
item => (
gettedTodosId.includes(item.id)
? { ...item, completed: gettedTodos[0].completed }
: item
),
));
})
.finally(() => {
setIsLoading(false);
setChangedTodo(null);
});
};

Choose a reason for hiding this comment

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

this function should be refactored and simplified because it is hard to read. pay attention to naming

const updateTitleTodo = (updatedTodo: Todo) => {
setErrorMessage('');
setChangedTodo([updatedTodo.id]);

setTodos(todos.map(todo => (
todo.id === updatedTodo.id
? {
...todo,
title: updatedTodo.title,
}
: todo
)));

return todoService.updateTodo(updatedTodo)
.catch((error) => {
setErrorMessage(Message.NoUpdateTodo);
throw error;
})
.finally(() => {
setChangedTodo(null);
});
};

const removeTodoTitle = (todoId: number) => {
setDeletedTodo([todoId]);

Choose a reason for hiding this comment

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

please memoize all functions what you passing to the child components

Choose a reason for hiding this comment

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

pay attention to this comment, use useMemo or useCallback for this purpose, it will optimize your code


return todoService.deleteTodos(todoId)
.then(() => {
setTodos(currentTodos => (
currentTodos.filter(todo => todo.id !== todoId)
));
})
.catch((error) => {
setTodos(todos);
setErrorMessage(Message.NoDeleteTodo);
throw error;
})
.finally(() => {
setDeletedTodo(null);
});
};

const visivleTodo = filterTodos(todos, todosStatus);
const activeTodos = todos.filter(todo => !todo.completed);

Choose a reason for hiding this comment

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

memoize

useEffect(() => {
getTodos(USER_ID)
.then(setTodos)
.catch(() => setErrorMessage(Message.NoLoadTotos));
}, []);

if (!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">
<Header
setTitleTodo={setTitleTodo}
titleTodo={titleTodo}
setErrorMessage={setErrorMessage}
onAddTodo={addTodo}
isLoading={isLoading}
setTodos={setTodos}
todos={todos}
updateTodosAllStatus={updateTodosAllStatus}
/>

{todos.length > 0 && (
<TodoList
todos={visivleTodo}
removeComplatedTodos={removeComplatedTodos}
removeTodoTitle={removeTodoTitle}
deletedTodo={deletedTodo}
updateTodoStatus={updateTodoStatus}
changedTodo={changedTodo}
updateTitleTodo={updateTitleTodo}
/>
)}
{tempTodo && (
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>
<>
<span data-cy="TodoTitle" className="todo__title">
{tempTodo.title}
</span>
<button
type="button"
className="todo__remove"
data-cy="TodoDelete"
>
×
</button>
</>
<div
data-cy="TodoLoader"
className={cn('modal overlay', {
'is-active': tempTodo.id === 0,
})}
>
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
)}
{(todos.length > 0 || tempTodo) && (
<Footer
todosStatus={todosStatus}
setTodosStatus={setTodosStatus}
todos={visivleTodo}
activeTodos={activeTodos}
removeTodo={removeComplatedTodos}
/>
)}
</div>

<ErrorNotification
errorMessage={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 getTodos = (userId: number) => {
return client.get<Todo[]>(`/todos?userId=${userId}`);
};

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

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

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

type Props = {
errorMessage: Message | '',
setErrorMessage: (m: Message | '') => void,
};

export const ErrorNotification: React.FC<Props> = ({
errorMessage,
setErrorMessage,
}) => {
setTimeout(() => {
setErrorMessage('');
}, 3000);

return (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !errorMessage,
})}
>
<button
aria-label="Close message"
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage('')}
/>
{errorMessage}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorNotification/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorNotification';
Loading
Loading