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

Open
wants to merge 5 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://andrii-kovalskyi02.github.io/react_todo-app-with-api/) and add it to the PR description.
252 changes: 239 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,250 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, {
useState,
useEffect,
useCallback,
useMemo,
} from 'react';
import { UserWarning } from './UserWarning';
import { TodoHeader } from './components/TodoHeader/TodoHeader';
import { TodoList } from './components/TodoList/TodoList';
import { TodoFooter } from './components/TodoFooter/TodoFooter';
import { TodoNotification } from './components/TodoNotification';
import {
getTodos,
createTodo,
updateTodo,
deleteTodo,
} from './api/todos';
import { TodoStatus } from './types/TodoStatus';
import { Todo } from './types/Todo';
import { TodoListContext } from './context/TodoListContext';

const USER_ID = 0;
const USER_ID = 10509;

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [filterBy, setFilterBy] = useState(TodoStatus.All);
const [hasError, setHasError] = useState(false);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [errorMessage, setErrorMessage] = useState('');
const [completedTodoIdList, setCompletedTodoIdList] = useState<number[]>([]);

const showErrorMessage = (message: string) => {
setHasError(true);
setErrorMessage(message);
};

const handleCloseButton = useCallback(() => {
setHasError(!hasError);
}, [hasError]);

useEffect(() => {
Copy link
Contributor

Choose a reason for hiding this comment

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

better to init all useEffects to the bottom before return

const timeoutId = setTimeout(() => {
setHasError(false);
}, 3000);

return () => {
clearTimeout(timeoutId);
};
}, [showErrorMessage]);

useEffect(() => {
getTodos(USER_ID)
.then(todoList => setTodos(todoList))
.catch(() => showErrorMessage('Unable to load todos'));
}, [USER_ID]);

const visibleTodos = useMemo(() => {
let visibleTodoArray = todos;
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
let visibleTodoArray = todos;
return todos.filter
and inside filter add condition for active and completed


switch (filterBy) {
case TodoStatus.Active:
visibleTodoArray = todos.filter(todo => !todo.completed);
break;

case TodoStatus.Completed:
visibleTodoArray = todos.filter(todo => todo.completed);
break;

case TodoStatus.All:
default:
break;
}

return visibleTodoArray;
}, [todos, filterBy]);

const activeTodosCount = useMemo(() => (

Choose a reason for hiding this comment

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

The dependency array for this useMemo should include 'todos' instead of 'visibleTodos'.

todos.filter(todo => !todo.completed).length
), [visibleTodos]);

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

const toggleAllTodos = useCallback(async () => {
const todosToToggle = areAllTodosCompleted
? todos.filter(todo => todo.completed)
: todos.filter(todo => !todo.completed);

setCompletedTodoIdList(todosToToggle.map(todo => todo.id));

try {
const updatedTodos = await Promise.all(todosToToggle
.map(todo => updateTodo(todo.id, { completed: !todo.completed })));

setTodos(currTodos => currTodos.map(todo => {
const updatedTodo = updatedTodos.find(task => task.id === todo.id);

return updatedTodo || todo;
}));
} catch {
showErrorMessage('Unable to update the todos');
} finally {
setCompletedTodoIdList([]);
}
}, [todos]);

const handleEnterKeyPress = useCallback((title: string) => {
setTempTodo({

Choose a reason for hiding this comment

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

It's better to use a unique identifier for the todo id instead of using Math.random(). As a variant, consider installing and using a library like 'uuid' to generate unique ids

id: Math.random(),
userId: USER_ID,
title,
completed: false,
});

createTodo({
userId: USER_ID,
title,
completed: false,
})
.then(fetchedTodo => setTodos(currTodos => [...currTodos, fetchedTodo]))
.catch(() => showErrorMessage('Unable to add a todo'))
.finally(() => setTempTodo(null));
}, [todos]);

const handleToggleButtonClick = useCallback(async (
todoId: number,
completed: boolean,
) => {
setCompletedTodoIdList([todoId]);

try {
const updatedTodo = await updateTodo(todoId, { completed: !completed });

setTodos(currTodos => currTodos.map(todo => {
return todo.id === todoId
? updatedTodo
: todo;
}));
} catch {
showErrorMessage('Unable to update a todo');
} finally {
setCompletedTodoIdList([]);
}
}, [todos]);

const handleTodoRename = useCallback(async (
todoId: number,
title: string,
) => {
setCompletedTodoIdList([todoId]);

try {
const updatedTodo = await updateTodo(todoId, { title });

setTodos(currTodos => currTodos.map(todo => {
return todo.id === todoId
? updatedTodo
: todo;
}));
} catch {
showErrorMessage('Unable to update a todo');
} finally {
setCompletedTodoIdList([]);
}
}, [todos]);

const handleRemoveButtonClick = useCallback(async (todoId: number) => {
setCompletedTodoIdList([todoId]);

try {
await deleteTodo(todoId);

setTodos(todos.filter(todo => todo.id !== todoId));
} catch {
showErrorMessage('Unable to delete a todo');
} finally {
setCompletedTodoIdList([]);
}
}, [todos]);

const handleFilterBy = useCallback((str: TodoStatus) => {
setFilterBy(str);
}, []);

const clearCompletedTodos = useCallback(async () => {
const completedTodoIds = todos.filter(todo => todo.completed)
.map(todo => todo.id);

setCompletedTodoIdList(completedTodoIds);
try {
await Promise.all(completedTodoIds.map(todoId => deleteTodo(todoId)));

setTodos(todos.filter(todo => !completedTodoIds.includes(todo.id)));
} catch {
showErrorMessage('Unable to delete the todos');
} finally {
setCompletedTodoIdList([]);
}
}, [todos]);

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">
<TodoHeader
isToggleAllButtonVisible={!!todos.length}
isTempTodoTrue={!!tempTodo}
showErrorMessage={showErrorMessage}
handleEnterKeyPress={handleEnterKeyPress}
onToggleAllButtonClick={toggleAllTodos}
areAllTodosCompleted={areAllTodosCompleted}
/>

<TodoListContext.Provider value={{
visibleTodos,
tempTodo,
completedTodoIdList,
handleTodoRename,
handleToggleButtonClick,
handleRemoveButtonClick,
}}
>
<TodoList />
</TodoListContext.Provider>

{todos.length > 0 && (
<TodoFooter
filterBy={filterBy}
itemsLeft={activeTodosCount}
handleFilterBy={handleFilterBy}
clearCompletedTodos={clearCompletedTodos}
completedTodos={todos.length - activeTodosCount}
/>
)}
</div>

<TodoNotification
hasError={hasError}
errorMessage={errorMessage}
handleCloseButton={handleCloseButton}
/>
</div>
);
};
18 changes: 18 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { NewTodo, Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

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

export const createTodo = (todo: NewTodo) => {
return client.post<Todo>('/todos', todo);
};

export const updateTodo = (todoId: number, todo: NewTodo) => {
return client.patch<Todo>(`/todos/${todoId}`, todo);
};

export const deleteTodo = (todoId: number) => {
return client.delete(`/todos/${todoId}`);
};
74 changes: 74 additions & 0 deletions src/components/TodoFooter/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import React, { useCallback } from 'react';
import classNames from 'classnames';
import { TodoStatus } from '../../types/TodoStatus';

type Props = {
handleFilterBy: (str: TodoStatus) => void,
filterBy: TodoStatus,
itemsLeft: number,
completedTodos: number,
clearCompletedTodos: () => void,
};

export const TodoFooter: React.FC<Props> = React.memo(({
handleFilterBy,
filterBy,
itemsLeft,
completedTodos,
clearCompletedTodos,
}) => {
const onClick = useCallback((event: React.MouseEvent<HTMLAnchorElement>) => {
const target = event.target as HTMLAnchorElement;

Choose a reason for hiding this comment

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

Using innerText might lead to potential issues with whitespaces and other formatting. Consider using a different approach to get the text content.


handleFilterBy(target.innerText as TodoStatus);
}, [handleFilterBy]);

return (
<footer className="todoapp__footer">
<span className="todo-count">
{`${itemsLeft} items left`}
</span>

<nav className="filter">
<a
href="#/"
className={classNames('filter__link', {
selected: TodoStatus.All === filterBy,
})}
onClick={onClick}
>
All
</a>

<a
href="#/active"
className={classNames('filter__link', {
selected: TodoStatus.Active === filterBy,
})}
onClick={onClick}
>
Active
</a>

<a
href="#/completed"
className={classNames('filter__link', {
selected: TodoStatus.Completed === filterBy,
})}
onClick={onClick}
>
Completed
</a>
</nav>

<button
type="button"
className="todoapp__clear-completed"
disabled={!completedTodos}
onClick={() => clearCompletedTodos()}

Choose a reason for hiding this comment

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

You can simplify the onClick handler to just 'onClick={clearCompletedTodos}' instead of using an arrow function.

>
Clear completed
</button>
</footer>
);
});
Loading