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

Open
wants to merge 2 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
312 changes: 298 additions & 14 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,310 @@
/* 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, useMemo, useRef, useState } from 'react';
import { UserWarning } from './UserWarning';
import {
deleteTodo,
getTodos,
patchTodo,
postTodo,
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 { Error } from './components/Error';

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

export const App: React.FC = () => {
// #region variables

const [value, setValue] = useState('');
const [editedValue, setEditedValue] = useState('');
const [todos, setTodos] = useState<Todo[]>([]);
const [isInputDisabled, setIsInputDisabled] = useState(false);
const [filter, setFilter] = useState(Filter.all);
const [error, setError] = useState('');
const [allCompleted, setAllCompleted] = useState(false);
const [editedInputById, setEditedInputById] = useState(-1);
const [key, setKey] = useState('');

const filteredTodos = useMemo(() => {
return todos.filter(todo => {
switch (filter) {
case Filter.active:
return !todo.completed;
case Filter.completed:
return todo.completed;
default:
return todo;
}
});
}, [filter, todos]);

const completedTodos = todos.filter(todo => todo.completed);
const inputRef = useRef<HTMLInputElement | null>(null);
const editedInputRef = useRef<HTMLInputElement | null>(null);
const nrOfActiveTodos = todos.filter(todo => !todo.completed).length;

// #endregion
// #region variables for loader

const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [idsOfTodosWithLoader, setIdsOfTodosWithLoader] = useState<number[]>(
[],
);

// #endregion
// #region useEffects

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => {
setError('Unable to load todos');
setTimeout(() => setError(''), 3000);
});
}, []);

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

useEffect(() => {
const isAllCompleted =
completedTodos.length > 0 && completedTodos.length === todos.length;

if (isAllCompleted) {
setAllCompleted(true);
} else if (allCompleted) {
setAllCompleted(false);
}
}, [allCompleted, completedTodos, todos.length]);

useEffect(() => {
if (editedInputRef.current && editedInputById) {
editedInputRef.current.focus();
}
}, [editedInputById]);

// #endregion
// #region functions

function onSubmit(event: React.FormEvent) {
event.preventDefault();
const trimmedValue = value.trim();

if (trimmedValue.length === 0) {
setError('Title should not be empty');

return;
}

const todo = {
id: 0,
userId: USER_ID,
title: trimmedValue,
completed: false,
};

setTempTodo(todo);
setIsInputDisabled(true);

postTodo(todo)
.then(_todo => {
setTodos(currentTodos => [...currentTodos, _todo]);
setValue('');
})
.catch(() => {
setError('Unable to add a todo');
setTimeout(() => setError(''), 3000);
})
.finally(() => {
setTempTodo(null);
setIsInputDisabled(false);
});
}

function deleteRequest(id: number) {
deleteTodo(id)
.then(() => {
setTimeout(() => {
setTodos(currentTodos =>
currentTodos.filter(_todo => _todo.id !== id),
);
}, 500);
})
.catch(() => {
setError('Unable to delete a todo');

setTimeout(() => setError(''), 3000);
})
.finally(() => {
setTimeout(() => {
setIdsOfTodosWithLoader(ids => ids.slice(1));
inputRef.current?.focus();
}, 500);
});
}

function onDelete(id: number) {
setIdsOfTodosWithLoader(ids => [...ids, id]);
deleteRequest(id);
}

function onDeleteSelected() {
todos.forEach(todo => {
if (todo.completed) {
const { id } = todo;

setIdsOfTodosWithLoader(ids => [...ids, id]);
deleteRequest(id);
}
});
}

function onSelect(id: number, todo: Todo) {
setIdsOfTodosWithLoader(ids => [...ids, id]);

patchTodo(id, todo)
.then(_todo => {
setTodos(currentTodos => {
return currentTodos.map(t => (_todo.id === t.id ? _todo : t));
});
if (editedInputById !== -1) {
setEditedInputById(-1);
}
})
.catch(() => {
setError('Unable to update a todo');
setTimeout(() => setError(''), 3000);
})
.finally(() => setIdsOfTodosWithLoader(ids => ids.slice(1)));
}

function toogleAll() {
const todosForToogle = todos.filter(todo =>
allCompleted ? todo.completed : !todo.completed,
);

setAllCompleted(!allCompleted);

todosForToogle.forEach(todo => {
const { id, completed } = todo;

onSelect(id, { ...todo, completed: !completed });
});
}

function setForm(id: number) {
const editedTodo = todos.find(todo => todo.id === id);

if (editedTodo) {
setEditedValue(editedTodo.title);
}

setEditedInputById(id);
}

function keyUp(event: React.KeyboardEvent) {
setKey(event.key);
}

function onSubmitChangedInput(event: React.FormEvent) {
event.preventDefault();
const editedTodo = todos.find(todo => todo.id === editedInputById) as Todo;
const trimmedValue = editedValue.trim();
const { title, id } = editedTodo;

if (title === trimmedValue) {
setEditedInputById(-1);

return;
}

if (trimmedValue.length === 0) {
setIdsOfTodosWithLoader(ids => [...ids, id]);
deleteRequest(id);

setTimeout(() => {
setEditedInputById(-1);
}, 500);

return;
}

editedTodo.title = trimmedValue;

onSelect(id, editedTodo);
}

// #endregion
// #region conditions

if (error) {
setTimeout(() => setError(''), 3000);
}

if (!USER_ID) {
return <UserWarning />;
}

if (key === 'Escape') {
setEditedInputById(-1);
setKey('');
}

// #endregion
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
value={value}
isInputDisabled={isInputDisabled}
allCompleted={allCompleted}
todos={todos}
inputRef={inputRef}
onSubmit={onSubmit}
setValue={setValue}
toogleAll={toogleAll}
/>
<TodoList
tempTodo={tempTodo}
editedInputById={editedInputById}
editedValue={editedValue}
filteredTodos={filteredTodos}
idsOfTodosWithLoader={idsOfTodosWithLoader}
editedInputRef={editedInputRef}
onDelete={onDelete}
onSelect={onSelect}
setForm={setForm}
setEditedValue={setEditedValue}
onSubmitChangedInput={onSubmitChangedInput}
keyUp={keyUp}
/>

{todos.length > 0 && (
<Footer
filter={filter}
nrOfActiveTodos={nrOfActiveTodos}
todos={todos}
setFilter={setFilter}
onDeleteSelected={onDeleteSelected}
/>
)}
</div>

<Error error={error} />
</div>
);
};
21 changes: 21 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 1889;

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

export const postTodo = (data: any) => {
return client.post<Todo>(`/todos`, data);
};

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

export const patchTodo = (id: number, data: any) => {
return client.patch<Todo>(`/todos/${id}`, data);
};
35 changes: 35 additions & 0 deletions src/components/Error/Error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import classNames from 'classnames';
import React from 'react';

interface Props {
error: string;
}

export const Error: React.FC<Props> = React.memo(({ error }) => {
return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification',
'is-danger',
'is-light',
'has-text-weight-normal',
{ hidden: error.length === 0 },
)}
>
<button data-cy="HideErrorButton" type="button" className="delete" />
{/* 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 */}
{error}
</div>
);
});

Error.displayName = 'Error';
1 change: 1 addition & 0 deletions src/components/Error/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Error';
Loading