Skip to content
Open

Develop #2181

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://AleksanderChaika.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": "^2.1.3",
"@mate-academy/students-ts-config": "*",
"@mate-academy/stylelint-config": "*",
"@types/node": "^20.14.10",
Expand Down
227 changes: 212 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,223 @@
/* 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, useState, useMemo } from 'react';
import cn from 'classnames';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
createTodo,
deleteTodo,
getTodos,
updateTodo,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { Footer } from './components/Footer';
import { TodoList } from './components/TodoList';
import { ErrorNotification } from './components/ErrorNotification';
import { ErrorMessage, Status } from './types/Enum';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMessage, setErrorMessage] = useState<ErrorMessage>(
ErrorMessage.None,
);

const [filter, setFilter] = useState<Status>(Status.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [newTodoTitle, setNewTodoTitle] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [loadingIds, setLoadingIds] = useState<number[]>([]);

const todoFieldRef = React.useRef<HTMLInputElement>(null);

const addTodo = (event: React.FormEvent) => {
event.preventDefault();
const trimmedTitle = newTodoTitle.trim();

if (!trimmedTitle) {
setErrorMessage(ErrorMessage.Title);
setTimeout(() => setErrorMessage(ErrorMessage.None), 3000);
todoFieldRef.current?.focus();

return;
}

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

createTodo({
userId: USER_ID,
title: trimmedTitle,
completed: false,
})
.then(newTodo => {
setTodos(prev => [...prev, newTodo]);
setNewTodoTitle('');
})
.catch(() => {
setErrorMessage(ErrorMessage.Add);
setTimeout(() => setErrorMessage(ErrorMessage.None), 3000);
})
.finally(() => {
setIsLoading(false);
setTempTodo(null);

setTimeout(() => {
todoFieldRef.current?.focus();
}, 0);
});
};

useEffect(() => {
getTodos()
.then(setTodos)
.catch(() => {
setErrorMessage(ErrorMessage.Load);
setTimeout(() => setErrorMessage(ErrorMessage.None), 3000);
});
}, []);

const removeTodo = (todoId: number) => {
setLoadingIds(prev => [...prev, todoId]);

return deleteTodo(todoId)
.then(() => {
setTodos(prev => prev.filter(todo => todo.id !== todoId));
})
.catch(error => {
setErrorMessage(ErrorMessage.Delete);
setTimeout(() => setErrorMessage(ErrorMessage.None), 3000);
throw error;
})
.finally(() => {
setLoadingIds(prev => prev.filter(id => id !== todoId));

setTimeout(() => {
todoFieldRef.current?.focus();
}, 0);
});
};

const onUpdate = (todoId: number, data: Partial<Todo>) => {
setLoadingIds(prev => [...prev, todoId]);

return updateTodo({ id: todoId, ...data })
.then(updatedTodo => {
setTodos(prev =>
prev.map(todo => (todo.id === todoId ? updatedTodo : todo)),
);
})
.catch(error => {
setErrorMessage(ErrorMessage.Update);
setTimeout(() => setErrorMessage(ErrorMessage.None), 3000);
throw error;
})
.finally(() => {
setLoadingIds(prev => prev.filter(id => id !== todoId));
});
};

const toggleAll = () => {
const allCompleted = todos.every(todo => todo.completed);
const targetStatus = !allCompleted;

todos.forEach(todo => {
if (todo.completed !== targetStatus) {
onUpdate(todo.id, { completed: targetStatus });
}
});
};

const clearCompleted = () => {
const completedTodos = todos.filter(todo => todo.completed);

completedTodos.forEach(todo => removeTodo(todo.id));
};

const visibleTodos = useMemo(() => {
return todos.filter(todo => {
if (filter === Status.Active) {
return !todo.completed;
}

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

return true;
});
}, [todos, filter]);

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

const activeCount = todos.filter(t => !t.completed).length;
const hasCompleted = todos.some(t => t.completed);
const isAllCompleted = todos.length > 0 && todos.every(t => t.completed);

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">
{todos.length > 0 && (
<button
type="button"
className={cn('todoapp__toggle-all', {
active: isAllCompleted,
})}
data-cy="ToggleAllButton"
onClick={toggleAll}
/>
)}

<form onSubmit={addTodo}>
<input
ref={todoFieldRef}
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={newTodoTitle}
onChange={e => setNewTodoTitle(e.target.value)}
disabled={isLoading}
autoFocus
/>
</form>
</header>

{(todos.length > 0 || tempTodo) && (
<TodoList
todos={visibleTodos}
tempTodo={tempTodo}
loadingIds={loadingIds}
onDelete={removeTodo}
onUpdate={onUpdate}
/>
)}

{todos.length > 0 && (
<Footer
activeCount={activeCount}
currentFilter={filter}
onFilterChange={setFilter}
hasCompleted={hasCompleted}
onClearCompleted={clearCompleted}
/>
)}
</div>

<ErrorNotification
message={errorMessage}
onClose={() => setErrorMessage(ErrorMessage.None)}
/>
</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 = 3160;

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

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

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

export const updateTodo = ({ id, ...data }: Partial<Todo>) => {
return client.patch<Todo>(`/todos/${id}`, data);
};
25 changes: 25 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React from 'react';
import cn from 'classnames';
import { ErrorMessage } from '../types/Enum';

interface Props {
message: ErrorMessage;
onClose: () => void;
}

export const ErrorNotification: React.FC<Props> = ({ message, onClose }) => (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !message,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>
{message}
</div>
);
51 changes: 51 additions & 0 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React from 'react';
import cn from 'classnames';
import { Status } from '../types/Enum';

interface Props {
activeCount: number;
currentFilter: Status;
onFilterChange: (status: Status) => void;
hasCompleted: boolean;
onClearCompleted: () => void;
}

export const Footer: React.FC<Props> = ({
activeCount,
currentFilter,
onFilterChange,
hasCompleted,
onClearCompleted,
}) => (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeCount} items left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(Status).map(status => (
<a
key={status}
href={`#/${status === Status.All ? '' : status}`}
className={cn('filter__link', {
selected: currentFilter === status,
})}
data-cy={`FilterLink${status.charAt(0).toUpperCase() + status.slice(1)}`}
onClick={() => onFilterChange(status)}
>
{status.charAt(0).toUpperCase() + status.slice(1)}
</a>
))}
</nav>

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