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 1.1 #1674

Open
wants to merge 6 commits 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 @@ -70,4 +70,4 @@ Filter todos by status `All` / `Active` / `Completed`:
- Install Prettier Extention and use this [VSCode settings](https://mate-academy.github.io/fe-program/tools/vscode/settings.json) to enable format on save.
- 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-loading-todos/) and add it to the PR description.
- Replace `<your_account>` with your Github username in the [DEMO LINK](https://sborichevskyi.github.io/react_todo-app-loading-todos/) and add it to the PR description.
246 changes: 63 additions & 183 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,204 +1,84 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import React, { useEffect, useState } from 'react';
import { UserWarning } from './UserWarning';
import { USER_ID } from './api/todos';
import { FilterEnum, getTodos, USER_ID } from './api/todos';
import { Todo } from './types/Todo';
import { Header } from './components/Header';
import { TodoList } from './components/TodoList';
import { Footer } from './components/Footer';
import { ErrorNotifications } from './components/ErrorNotifications';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}

return (
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<header className="todoapp__header">
{/* this button should have `active` class only if all todos are completed */}
<button
type="button"
className="todoapp__toggle-all active"
data-cy="ToggleAllButton"
/>

{/* Add a todo on form submit */}
<form>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
/>
</form>
</header>

<section className="todoapp__main" data-cy="TodoList">
{/* This is a completed todo */}
<div data-cy="Todo" className="todo completed">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
checked
/>
</label>

<span data-cy="TodoTitle" className="todo__title">
Completed Todo
</span>

{/* Remove button appears only on hover */}
<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>

{/* overlay will cover the todo while it is being deleted or updated */}
<div data-cy="TodoLoader" className="modal overlay">
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
const [visibleTodos, setVisibleTodos] = useState<Todo[]>([]);
const [allTodos, setAllTodos] = useState<Todo[]>([]);

{/* This todo is an active todo */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>
const [, setLoading] = useState(false);

<span data-cy="TodoTitle" className="todo__title">
Not Completed Todo
</span>
<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
const [error, setError] = useState(false);
const [errorMessage, setErrorMessage] = useState('');

<div data-cy="TodoLoader" className="modal overlay">
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
const [inputText, setInputText] = useState('');

{/* This todo is being edited */}
<div data-cy="Todo" className="todo">
<label className="todo__status-label">
<input
data-cy="TodoStatus"
type="checkbox"
className="todo__status"
/>
</label>
const [selectedFilter, setSelectedFilter] = useState(FilterEnum.ALL);

{/* This form is shown instead of the title and remove button */}
<form>
<input
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value="Todo is being edited now"
/>
</form>
const [completedLentgh, setCompletedLentgh] = useState(0);

<div data-cy="TodoLoader" className="modal overlay">
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
useEffect(() => {
setLoading(true);
getTodos()
.then(todosFromServer => {
setAllTodos(todosFromServer);
setVisibleTodos(todosFromServer);
setCompletedLentgh(
todosFromServer.filter(todo => !todo.completed).length,
);
})
.catch(() => {
setError(true);
setErrorMessage('Unable to load todos');
})
.finally(() => setLoading(false));
}, []);

{/* This todo is in loadind state */}
<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">
Todo is being saved now
</span>
if (!USER_ID) {
return <UserWarning />;
}

<button type="button" className="todo__remove" data-cy="TodoDelete">
×
</button>
return (
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

{/* 'is-active' class puts this modal on top of the todo */}
<div data-cy="TodoLoader" className="modal overlay is-active">
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
</div>
</section>
<div className="todoapp__content">
<Header
visibleTodos={visibleTodos}
inputText={inputText}
error={error}
setInputText={setInputText}
setError={setError}
setErrorMessage={setErrorMessage}
setVisibleTodos={setVisibleTodos}
/>
<TodoList visibleTodos={visibleTodos} />

{/* Hide the footer if there are no todos */}
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
3 items left
</span>

{/* Active link should have the 'selected' class */}
<nav className="filter" data-cy="Filter">
<a
href="#/"
className="filter__link selected"
data-cy="FilterLinkAll"
>
All
</a>

<a
href="#/active"
className="filter__link"
data-cy="FilterLinkActive"
>
Active
</a>

<a
href="#/completed"
className="filter__link"
data-cy="FilterLinkCompleted"
>
Completed
</a>
</nav>

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
>
Clear completed
</button>
</footer>
{allTodos.length > 0 && (
<Footer
selectedFilter={selectedFilter}
setSelectedFilter={setSelectedFilter}
setVisibleTodos={setVisibleTodos}
completedLentgh={completedLentgh}
allTodos={allTodos}
/>
)}
</div>

{/* DON'T use conditional rendering to hide the notification */}
{/* Add the 'hidden' class to hide the message smoothly */}
<div
data-cy="ErrorNotification"
className="notification is-danger is-light has-text-weight-normal"
>
<button data-cy="HideErrorButton" type="button" className="delete" />
{/* show only one message at a time */}
Unable to load todos
<br />
Title should not be empty
<br />
Unable to add a todo
<br />
Unable to delete a todo
<br />
Unable to update a todo
</div>
<ErrorNotifications
error={error}
errorMessage={errorMessage}
setError={setError}
setErrorMessage={setErrorMessage}
/>
</div>
);
};
93 changes: 91 additions & 2 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,99 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 0;
export const USER_ID = 2248;

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

// Add more methods here
export const getCompletedTodos = (visibleTodos: Todo[]) => {
return visibleTodos.filter(todo => todo.completed);
};

export const getActiveTodos = (visibleTodos: Todo[]) => {
return visibleTodos.filter(todo => !todo.completed);
};

export const createNewTodo = async (
inputText: string,
setError: React.Dispatch<React.SetStateAction<boolean>>,
setErrorMessage: React.Dispatch<React.SetStateAction<string>>,
setVisibleTodos: React.Dispatch<React.SetStateAction<Todo[]>>,
setInputText: React.Dispatch<React.SetStateAction<string>>,
) => {
try {
const todos = await getTodos();

const newId =
todos.length === 0 ? 1 : Math.max(...todos.map(todo => todo.id)) + 1;

const newTodo: Todo = {
id: newId,
userId: 2248,
title: inputText.trim(),
completed: false,
};

await client.post(`/todos?userId=${USER_ID}`, newTodo);
setVisibleTodos(prevTodos => [...prevTodos, newTodo]);
setInputText('');
} catch (error) {
setError(true);
setErrorMessage('Unable to create a new todo');
}
};

export enum FilterEnum {
ALL = 'all',
ACTIVE = 'active',
COMPLETED = 'completed',
}

export const addTodo = (
inputText: string,
setError: React.Dispatch<React.SetStateAction<boolean>>,
setErrorMessage: React.Dispatch<React.SetStateAction<string>>,
setVisibleTodos: React.Dispatch<React.SetStateAction<Todo[]>>,
setInputText: React.Dispatch<React.SetStateAction<string>>,
) => {
if (inputText.trim() === '') {
setError(true);
setErrorMessage('Title should not be empty');
} else {
createNewTodo(
inputText,
setError,
setErrorMessage,
setVisibleTodos,
setInputText,
);
}
};

export const filterTodos = async (
curFilter: FilterEnum,
setVisibleTodos: React.Dispatch<React.SetStateAction<Todo[]>>,
allTodos: Todo[],
) => {
switch (curFilter) {
case FilterEnum.ALL:
setVisibleTodos(allTodos);

break;
case FilterEnum.ACTIVE:
const activeTodos = getActiveTodos(allTodos);

setVisibleTodos(activeTodos);

break;
case FilterEnum.COMPLETED:
const completedTodos = getCompletedTodos(allTodos);

setVisibleTodos(completedTodos);

break;
default:
throw new Error(`Unsupported filter type: ${curFilter}`);
}
};
Loading
Loading