Skip to content
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://tavokina.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.

267 changes: 251 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,261 @@
/* 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, useRef, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import * as todoService from './api/todos';
import { Todo } from './types/Todo';
import classNames from 'classnames';
import { TodoList } from './components/TodoList';
import { TodoItem } from './components/TodoItem';
import { NewTodo } from './types/NewTodo';
import { ErrorMessages } from './types/ErrorMessages';
import { Status } from './types/Status';
import { Filter } from './components/Filter';

export const App: React.FC = () => {
if (!USER_ID) {
const [todos, setTodos] = useState<Todo[]>([]);
const [title, setTitle] = useState('');
const [todoStatus, setTodoStatus] = useState(Status.All);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [loadingIds, setLoadingIds] = useState<number[]>([]);

const normalizedTitle = title.trim();
const isAllCompleted = todos.every(todo => todo.completed);
const hasCompleted = todos.some(todo => todo.completed);
const filteringByStatus = todos.filter(todo => {
if (todoStatus === Status.Active) {
return !todo.completed;
}

if (todoStatus === Status.Completed) {
return todo.completed;
}

return true;
});

const newTodo = (todoTitle: string): NewTodo => {
return {
userId: todoService.USER_ID,
title: todoTitle,
completed: false,
};
};

const handleAppSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

if (!normalizedTitle) {
setErrorMessage(ErrorMessages.Title);

return;
}

setTempTodo({
...newTodo(normalizedTitle),
id: 0,
});
todoService
.addTodo(newTodo(normalizedTitle))
.then(addedTodo => {
setTodos([...todos, addedTodo]);
setTitle('');
setTempTodo(null);
})
.catch(() => {
setErrorMessage(ErrorMessages.Add);
setTempTodo(null);
});
};

/* get todos */
useEffect(() => {
todoService
.getTodos()
.then(setTodos)
.catch(() => setErrorMessage(ErrorMessages.Load));
}, []);

/* errors */
useEffect(() => {
if (!errorMessage) {
return;
}

const timer = setTimeout(() => setErrorMessage(null), 3000);

return () => clearTimeout(timer);
}, [errorMessage]);

/* input focus */
const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
inputRef.current?.focus();
}, [tempTodo]);

/* deleting */
function deleteTodo(todoId: number) {
setLoadingIds(prev => [...prev, todoId]);
todoService
.deleteTodo(todoId)
.then(() => setTodos(prev => prev.filter(todo => todo.id !== todoId)))
.catch(() => {
setErrorMessage(ErrorMessages.Delete);
setTempTodo(null);
})
.finally(() => {
setLoadingIds(loadingIds.filter(id => id !== todoId));
inputRef?.current?.focus();
});
}

const clearCompleted = () => {
todos.filter(todo => todo.completed).forEach(todo => deleteTodo(todo.id));
};

/* toggle */
const onToggle = (todo: Todo) => {
setLoadingIds(prev => [...prev, todo.id]);
const toggled = { ...todo, completed: !todo.completed };

todoService
.updateTodo(toggled)
.then(toggledTodo => {
setTodos(prev =>
prev.map(t => (t.id === toggledTodo.id ? toggledTodo : t)),
);
})
.catch(() => setErrorMessage(ErrorMessages.Update))
.finally(() => setLoadingIds(prev => prev.filter(id => id !== todo.id)));
};

const toggleAll = () => {
if (hasCompleted && !isAllCompleted) {
return todos.filter(todo => !todo.completed).forEach(t => onToggle(t));
}

return todos.forEach(todo => onToggle(todo));
};

/* update */
const onUpdate = (updatedTodo: Todo) => {
setLoadingIds(prev => [...prev, updatedTodo.id]);

return todoService
.updateTodo(updatedTodo)
.then(() =>
setTodos(prev =>
prev.map(t => (t.id === updatedTodo.id ? updatedTodo : t)),
),
)
.catch(() => {
setErrorMessage(ErrorMessages.Update);
throw new Error();
})
.finally(() =>
setLoadingIds(prev => prev.filter(id => id !== updatedTodo.id)),
);
};

if (!todoService.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 className="todoapp__header">
{/* this button should have `active` class only if all todos are completed */}
{todos.length > 0 && (
<button
type="button"
className={classNames('todoapp__toggle-all', {
active: isAllCompleted,
})}
data-cy="ToggleAllButton"
onClick={toggleAll}
/>
)}

{/* Add a todo on form submit */}
<form onSubmit={e => handleAppSubmit(e)}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={title}
onChange={e => setTitle(e.target.value)}
ref={inputRef}
disabled={tempTodo !== null}
/>
</form>
</header>

<TodoList
todos={filteringByStatus}
onDelete={deleteTodo}
loadingIds={loadingIds}
onChecked={onToggle}
onChange={onUpdate}
/>

{tempTodo && (
<TodoItem
todo={tempTodo}
isLoading={true}
deleteItem={() => {}}
isComplete={() => {}}
isChange={() => Promise.resolve()}
/>
)}

{/* Hide the footer if there are no todos */}
{todos.length > 0 && (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{todos.filter(todo => !todo.completed).length} items left
</span>

{/* Active link should have the 'selected' class */}
<Filter todoStatus={todoStatus} onChangeStatus={setTodoStatus} />

{/* this button should be disabled if there are no completed todos */}
<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={clearCompleted}
disabled={!hasCompleted}
>
Clear completed
</button>
</footer>
)}
</div>

<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{
hidden: !errorMessage,
},
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={() => setErrorMessage(null)}
/>
{/* show only one message at a time */}
{errorMessage}
</div>
</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 = 4201;

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

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

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

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

type Props = {
todoStatus: Status;
onChangeStatus: Dispatch<SetStateAction<Status>>;
};

export const Filter: React.FC<Props> = ({ todoStatus, onChangeStatus }) => {
return (
<nav className="filter" data-cy="Filter">
{Object.values(Status).map(status => (
<a
key={status}
href={status === Status.All ? '#/' : `#/${status.toLowerCase()}`}
className={classNames('filter__link', {
selected: status === todoStatus,
})}
data-cy={`FilterLink${status}`}
onClick={() => onChangeStatus(status)}
>
{status}
</a>
))}
</nav>
);
};
Loading
Loading