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

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
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://marichkamt.github.io/react_todo-app-with-api/) and add it to the PR description.
257 changes: 158 additions & 99 deletions package-lock.json

Large diffs are not rendered by default.

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
20 changes: 4 additions & 16 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,14 @@
/* 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 { UserWarning } from './UserWarning';

const USER_ID = 0;
import { USER_ID } from './api/todos';
import { TodoApp } from './components/TodoApp';

export const App: React.FC = () => {
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>
);
return <TodoApp />;
};
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 = 11946;

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

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

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

export const updateTodo = (id: number, data: Partial<Todo>) => {
return client.patch<Todo>(`/todos/${id}`, data);
};
128 changes: 128 additions & 0 deletions src/components/EditForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { useEffect, useRef, useState } from 'react';
import { Todo } from '../types/Todo';
import { Loader } from './Loader';

type Props = {
editTodo: Todo | null;
setEditTodo: (todo: Todo | null) => void;
updtTodo: (id: number, data: Partial<Todo>) => Promise<Todo>;
loadingTodosIds: number[];
setLoadingTodosIds: (todos: number[]) => void;
deleteTodo: (id: number) => Promise<void>;
};

export const EditForm: React.FC<Props> = ({
editTodo,
setEditTodo,
updtTodo,
loadingTodosIds,
setLoadingTodosIds,
deleteTodo,
}) => {
const [newValue, setNewValue] = useState(editTodo?.title || '');
const editField = useRef<HTMLInputElement>(null);

const isTodoLoading = editTodo
? loadingTodosIds.includes(editTodo.id)
: false;

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

const onKeyEscape = () => {
setEditTodo(null);
};

const prevValue = editTodo?.title || '';

const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();

if (prevValue === newValue) {
setEditTodo(null);

return;
}

if (editTodo) {
setLoadingTodosIds([...loadingTodosIds, editTodo.id]);

updtTodo(editTodo.id, { title: newValue?.trim() })
.then(() => {
setEditTodo(null);
})
.catch(() => {
setEditTodo(editTodo);
})
.finally(() =>
setLoadingTodosIds(loadingTodosIds.filter(id => id !== editTodo.id)),
);
}
};

const handleOnBlur = (event: React.FormEvent) => {
if (newValue?.trim().length === 0) {
setLoadingTodosIds([...loadingTodosIds, editTodo?.id || 0]);

if (editTodo) {
deleteTodo(editTodo.id).finally(() =>
setLoadingTodosIds(loadingTodosIds.filter(id => id !== editTodo.id)),
);
}

return;
}

handleSubmit(event);
};

const onKeyEnter = (event: React.KeyboardEvent) => {
event.preventDefault();

if (!newValue?.trim().length) {
setLoadingTodosIds([...loadingTodosIds, editTodo?.id || 0]);

if (editTodo) {
deleteTodo(editTodo.id).finally(() =>
setLoadingTodosIds(loadingTodosIds.filter(id => id !== editTodo.id)),
);
}

return;
}

handleSubmit(event);
};

const onKeyDownHandle = (event: React.KeyboardEvent) => {
switch (event.key) {
case 'Enter':
onKeyEnter(event);
break;
case 'Escape':
onKeyEscape();
break;
}
};

return (
<>
<form>
<input
data-cy="TodoTitleField"
type="text"
className="todo__title-field"
placeholder="Empty todo will be deleted"
value={newValue}
ref={editField}
onBlur={handleOnBlur}
onChange={event => setNewValue(event.target.value)}
onKeyDown={onKeyDownHandle}
/>
</form>

{isTodoLoading && <Loader isLoading={isTodoLoading} />}
</>
);
};
31 changes: 31 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import classNames from 'classnames';
import { Errors } from '../enums/Errors';

interface ErrorNotificationProps {
errorMessage: Errors | null;
clearErrorMessage: () => void;
}

export const ErrorNotification: React.FC<ErrorNotificationProps> = ({
errorMessage,
clearErrorMessage,
}) => {
return (
<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={clearErrorMessage}
/>

{errorMessage}
</div>
);
};
18 changes: 18 additions & 0 deletions src/components/Loader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import classNames from 'classnames';
import React from 'react';

type Props = {
isLoading: boolean;
};

export const Loader: React.FC<Props> = ({ isLoading }) => (
<div
data-cy="TodoLoader"
className={classNames('modal', 'overlay', {
'is-active': isLoading,
})}
>
<div className="modal-background has-background-white-ter" />
<div className="loader" />
</div>
);
148 changes: 148 additions & 0 deletions src/components/TodoApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createTodo, deleteTodo, getTodos, updateTodo } from '../api/todos';
import { Todo } from '../types/Todo';
import { TodoHeader } from './TodoHeader';
import { TodoList } from './TodoList';
import { TodoFooter } from './TodoFooter';
import { Errors } from '../enums/Errors';
import { ErrorNotification } from './ErrorNotification';
import { FilteredTodos } from '../enums/FilteresTodos';
import handleFilteredTodos from '../utils/handleFilteredTodos';

export const TodoApp: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [errorMessage, setErrorMessage] = useState<Errors | null>(null);
const [loadingTodosIds, setLoadingTodosIds] = useState<number[]>([]);
const [filterSelected, setFilterSelected] = useState<FilteredTodos>(
FilteredTodos.all,
);
const inputField = useRef<HTMLInputElement>(null);

const preparedTodos = handleFilteredTodos(todos, filterSelected);
const activeTodos = handleFilteredTodos(todos, FilteredTodos.active);
const completedTodos = handleFilteredTodos(todos, FilteredTodos.completed);

const clearErrorMessage = () => {
setErrorMessage(null);
};

// eslint-disable-next-line react-hooks/exhaustive-deps
const showError = (error: Errors) => {
setErrorMessage(error);
};

useEffect(() => {
const clearError = setTimeout((error: Errors) => {
setErrorMessage(error);
}, 3000);

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

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => showError(Errors.LoadTodos));
}, []);

const addTodo = (newTodo: Omit<Todo, 'id'>) => {
return createTodo(newTodo)
.then(todo => {
setTodos(currentTodos => [...currentTodos, todo]);
})
.catch(error => {
showError(Errors.AddTodo);
throw error;
});
};

const delTodo = useCallback(
(id: number): Promise<void> => {
return deleteTodo(id)
.then(() => {
setTodos(currentTodos => currentTodos.filter(todo => todo.id !== id));
inputField.current?.focus();
})
.catch((error: unknown) => {
showError(Errors.DeleteTodo);
throw error;
});
},
[setTodos, inputField, showError],
);

const updtTodo: (id: number, data: Partial<Todo>) => Promise<Todo> = (
id: number,
data: Partial<Todo>,
) => {
return updateTodo(id, data)
.then(updtdTodo => {
setTodos(currentTodos => {
const newTodos = [...currentTodos];
const index = newTodos.findIndex(post => post.id === id);

newTodos.splice(index, 1, updtdTodo);

return newTodos;
});

return updtdTodo;
})
.catch(error => {
setErrorMessage(Errors.UpdateTodo);
throw error;
});
};

const onCompleteDelete = useMemo(() => {
return () => {
todos.filter(todo => todo.completed).forEach(todo => delTodo(todo.id));
};
}, [todos, delTodo]);

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

<div className="todoapp__content">
<TodoHeader
addTodo={addTodo}
preparedTodos={preparedTodos}
setTempTodo={setTempTodo}
setErrorMessage={setErrorMessage}
clearErrorMessage={clearErrorMessage}
inputField={inputField}
loadingTodosIds={loadingTodosIds}
setLoadingTodosIds={setLoadingTodosIds}
updtTodo={updtTodo}
todos={todos}
/>

<TodoList
deleteTodo={delTodo}
tempTodo={tempTodo}
preparedTodos={preparedTodos}
updtTodo={updtTodo}
loadingTodosIds={loadingTodosIds}
setLoadingTodosIds={setLoadingTodosIds}
/>

{todos.length > 0 && (
<TodoFooter
filterSelected={filterSelected}
setFilterSelected={setFilterSelected}
activeTodos={activeTodos}
completedTodos={completedTodos}
onCompleteDelete={onCompleteDelete}
/>
)}
</div>

<ErrorNotification
errorMessage={errorMessage}
clearErrorMessage={clearErrorMessage}
/>
</div>
);
};
Loading
Loading