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

add task solution #1509

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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://tonni004.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
264 changes: 250 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,262 @@
/* 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, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { UserWarning } from './UserWarning';
import { getTodos, USER_ID } from './api/api';
import { Header } from './components/Header/Header';
import { TodoList } from './components/TodoList/TodoList';
import { Footer } from './components/Footer/Footer';
import { Todo } from './types/Todo';
import { Notification } from './components/Notification/Notification';
import * as todoService from './api/api';

const USER_ID = 0;
export enum Filter {
All = 'all',
Active = 'active',
Completed = 'completed',
}

export const App: React.FC = () => {
const [todosFromServer, setTodosFromServer] = useState<Todo[]>([]);
const [filter, setFilter] = useState<Filter>(Filter.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingTodoIds, setLoadingTodoIds] = useState<number[]>([]);
const [notification, setNotification] = useState({
isHidden: true,
message: '',
});

const inputRef = useRef<HTMLInputElement>(null);

const showNotification = (message: string) => {
setNotification({ isHidden: false, message });
setTimeout(() => setNotification({ isHidden: true, message: '' }), 3000);
};

const filterTodos = useCallback((todos: Todo[], filterBy: Filter): Todo[] => {
switch (filterBy) {
case Filter.Completed:
return todos.filter(todo => todo.completed);

case Filter.Active:
return todos.filter(todo => !todo.completed);

default:
return todos;
}
}, []);

const visibleTodos = useMemo(
() => filterTodos(todosFromServer, filter),
[filterTodos, todosFromServer, filter],
);

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

const allTodosCompleted = useMemo(
() => activeTodosCount === 0,
[activeTodosCount],
);

const hasCompletedTodos = useMemo(
() => todosFromServer.some(todo => todo.completed),
[todosFromServer],
);

const handleAddTodo = (title: string) => {
setNotification({ isHidden: true, message: '' });

const trimmedTitle = title.trim();

if (!trimmedTitle.length) {
showNotification('Title should not be empty');

return Promise.reject('Title is empty');
}

setTempTodo({
title: trimmedTitle,
userId: USER_ID,
completed: false,
id: 0,
});

return todoService
.createTodo({ title: trimmedTitle, userId: USER_ID, completed: false })
.then(newTodo => {
setTodosFromServer(currentTodos => [...currentTodos, newTodo]);
})
.catch(error => {
showNotification('Unable to add a todo');
throw new Error(error);
})
.finally(() => {
setTempTodo(null);
});
};

const handleDeleteTodo = (todoId: number) => {
setLoadingTodoIds([todoId]);

return todoService
.deleteTodo(todoId)
.then(() => {
setTodosFromServer(curr => curr.filter(todo => todo.id !== todoId));
})
.catch(error => {
showNotification('Unable to delete a todo');
throw new Error(error);
})
.finally(() => {
setLoadingTodoIds([]);
if (inputRef.current) {
inputRef.current.focus();
}
});
};

const handleClearCompletedTodos = () => {
const completedTodoIds = todosFromServer
.filter(todo => todo.completed)
.map(todo => todo.id);

setLoadingTodoIds(completedTodoIds);
Promise.all(
completedTodoIds.map(id =>
todoService
.deleteTodo(id)
.then(() => {
setTodosFromServer(curr => curr.filter(todo => todo.id !== id));
})
.catch(error => {
showNotification('Unable to delete a todo');
throw new Error(error);
})
.finally(() => {
setLoadingTodoIds([]);
if (inputRef.current) {
inputRef.current.focus();
}
}),
),
);
};

const handleUpdateTodo = (updatedTodo: Todo) => {
setLoadingTodoIds([updatedTodo.id]);

return todoService
.updateTodo(updatedTodo)
.then(receivedTodo => {
setTodosFromServer(curr =>
curr.map(todo => (todo.id === receivedTodo.id ? receivedTodo : todo)),
);
})
.catch(error => {
showNotification('Unable to update a todo');
throw new Error(error);
})
.finally(() => {
setLoadingTodoIds([]);
});
};

const handleToggleAllTodoStatus = () => {
let todosToChange = [];

if (allTodosCompleted) {
todosToChange = [...todosFromServer];
} else {
todosToChange = todosFromServer.filter(todo => !todo.completed);
}

const todoToChangeIds = todosToChange.map(todo => todo.id);

setLoadingTodoIds(todoToChangeIds);
Promise.all(
todosToChange.map(todoToChange => {
const { id, completed, title, userId } = todoToChange;

todoService
.updateTodo({ id, completed: !completed, title, userId })
.then(receivedTodo => {
setTodosFromServer(curr =>
curr.map(todo =>
todo.id === receivedTodo.id ? receivedTodo : todo,
),
);
})
.catch(error => {
showNotification('Unable to update a todo');
throw new Error(error);
})
.finally(() => {
setLoadingTodoIds([]);
});
}),
);
};

useEffect(() => {
getTodos()
.then(setTodosFromServer)
.catch(() => {
showNotification('Unable to load 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">
<Header
inputRef={inputRef}
hasTodos={!!todosFromServer.length}
allCompletedTodos={allTodosCompleted}
onAddTodo={handleAddTodo}
onToggleAll={handleToggleAllTodoStatus}
/>

{!!todosFromServer.length && (
<TodoList
todos={visibleTodos}
tempTodo={tempTodo}
onDeleteTodo={handleDeleteTodo}
loading={loadingTodoIds}
onUpdateTodo={handleUpdateTodo}
/>
)}

{!!todosFromServer.length && (
<Footer
activeTodosCount={activeTodosCount}
currFilter={filter}
hasCompletedTodos={hasCompletedTodos}
onFilter={setFilter}
onClearCompletedTodos={handleClearCompletedTodos}
/>
)}
</div>

<Notification
message={notification.message}
isHidden={notification.isHidden}
onClose={() => setNotification({ ...notification, isHidden: true })}
/>
</div>
);
};
22 changes: 22 additions & 0 deletions src/api/api.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClients';

export const USER_ID = 1799;

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

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

export function deleteTodo(todoId: number) {
return client.delete(`/todos/${todoId}`);
}

export function updateTodo(data: Todo): Promise<Todo> {
const { id } = data;

return client.patch(`/todos/${id}`, data);
}
57 changes: 57 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import classNames from 'classnames';
import { Filter } from '../../App';

type Props = {
activeTodosCount: number;
currFilter: Filter;
hasCompletedTodos: boolean;
onFilter: (newFilter: Filter) => void;
onClearCompletedTodos: () => void;
};

export const Footer: React.FC<Props> = ({
activeTodosCount,
currFilter,
hasCompletedTodos,
onFilter,
onClearCompletedTodos,
}) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{`${activeTodosCount} items left`}
</span>

<nav className="filter" data-cy="Filter">
{Object.values(Filter).map(filter => {
const capitalizedFilter =
filter[0].toUpperCase() + filter.slice(1).toLowerCase();

return (
<a
key={filter}
href={`#/${filter === Filter.All ? '' : filter}`}
className={classNames('filter__link', {
selected: currFilter === filter,
})}
data-cy={`FilterLink${capitalizedFilter}`}
onClick={() => onFilter(filter)}
>
{capitalizedFilter}
</a>
);
})}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={onClearCompletedTodos}
disabled={!hasCompletedTodos}
>
Clear completed
</button>
</footer>
);
};
Loading
Loading