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://NazarenkoAnna.github.io/react_todo-app-with-api/) and add it to the PR description.
231 changes: 216 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,227 @@
/* 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, { useCallback, useEffect, useMemo, useState } from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import {
updateTodo,
addTodo,
deleteTodo,
getTodos,
USER_ID,
} from './api/todos';
import { Todo } from './types/Todo';
import { TodoFooter } from './components/TodoFooter';
import { ErrorNotification } from './components/ErrorNotification';
import { TodoList } from './components/TodoList';
import { TodoHeader } from './components/TodoHeader';
import { Filter } from './types/Filter';
import { Error } from './types/ErrorMsg';
import { TodoItem } from './components/TodoItem';

export const App: React.FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [errorMsg, setErrorMsg] = useState<Error | ''>('');
const [isLoading, setIsLoading] = useState(false);
const [filter, setFilter] = useState<Filter>(Filter.All);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [todoTitle, setTodoTitle] = useState('');
const [isSubmiting, setIsSubmiting] = useState(false);
const [processingId, setProcessingId] = useState<number[]>([]);

useEffect(() => {
setIsLoading(true);
setErrorMsg('');
getTodos()
.then(setTodos)
.catch(() => {
setErrorMsg(Error.Fetch);
})
.finally(() => {
setIsLoading(false);
});
}, []);

const handleErrorClose = useCallback(() => {
setErrorMsg('');
}, []);

const onAddTodo = (title: string) => {
setIsSubmiting(true);
setErrorMsg('');

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

setTempTodo(newTodo);

addTodo(newTodo)
.then(created => {
setTodos(prev => [...prev, created]);
setTodoTitle('');
})
.catch(err => {
setTimeout(() => setErrorMsg(Error.Add), 0);
throw err;
})
.finally(() => {
setTempTodo(null);
setIsSubmiting(false);
});
};

const handleOnDelete = (id: number) => {
setProcessingId(prev => [...prev, id]);
deleteTodo(id)
.then(() => {
setTodos(prev => prev.filter(todo => todo.id !== id));
})
.catch(() => {
setErrorMsg(Error.Delete);
})
.finally(() => {
setProcessingId(prev => prev.filter(i => i !== id));
});
};

const onDeleteCompletedTodos = () => {
const completedIds = todos.filter(todo => todo.completed);

if (completedIds.length === 0) {
return;
}

completedIds.forEach(todo => {
handleOnDelete(todo.id);
});
};

const allTodosCompleted = useMemo(
() => todos.length > 0 && todos.every(todo => todo.completed),
[todos],
);

const handleToggleTodo = (todo: Todo) => {
const id = todo.id;

setProcessingId(prev => [...prev, id]);
setErrorMsg('');

updateTodo(id, { completed: !todo.completed })
.then(updatedTodo => {
setTodos(current =>
current.map(item => (item.id === id ? updatedTodo : item)),
);
})
.catch(() => {
setErrorMsg(Error.Update);
})
.finally(() => {
setProcessingId(prev => prev.filter(i => i !== id));
});
};

const handleToggleAll = () => {
setErrorMsg('');

const status = allTodosCompleted;

const activeItems = todos.filter(todo => todo.completed === status);

activeItems.forEach(todo => {
handleToggleTodo(todo);
});
};

const handleUpdateTodo = (
todo: Todo,
data: { title: string },
): Promise<void> => {
setErrorMsg('');
setProcessingId(prev => [...prev, todo.id]);

return updateTodo(todo.id, data)
.then(updatedTodo => {
setTodos(current =>
current.map(item => (item.id === todo.id ? updatedTodo : item)),
);
})
.catch(err => {
setErrorMsg(Error.Update);
throw err;
})
.finally(() => {
setProcessingId(prev => prev.filter(i => i !== todo.id));
});
};

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

const activeTodos = useMemo(
() => todos.filter(todo => !todo.completed).length,
[todos],
);

const completedTodos = useMemo(
() => todos.filter(todo => todo.completed).length > 0,
[todos],
);

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>
<div className="todoapp">
<h1 className="todoapp__title">todos</h1>

<div className="todoapp__content">
<TodoHeader
todos={todos}
isSubmiting={isSubmiting}
todoTitle={todoTitle}
setTodoTitle={setTodoTitle}
onAddTodo={onAddTodo}
setErrorMsg={setErrorMsg}
allTodosCompleted={allTodosCompleted}
toggleAll={handleToggleAll}
/>

<TodoList
todos={filteredTodos}
isLoading={isLoading}
processingId={processingId}
onDelete={handleOnDelete}
onToggle={handleToggleTodo}
onUpdate={handleUpdateTodo}
/>

{tempTodo && <TodoItem todo={tempTodo} isSubmiting />}

{todos.length !== 0 && (
<TodoFooter
activeTodos={activeTodos}
completedTodos={completedTodos}
filter={filter}
onFilterChange={setFilter}
onDeleteCompletedTodos={onDeleteCompletedTodos}
/>
)}
</div>

<ErrorNotification errorMsg={errorMsg} onClose={handleErrorClose} />
</div>
);
};
23 changes: 23 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Todo } from '../types/Todo';
import { client } from '../utils/fetchClient';

export const USER_ID = 4060;

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

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

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);
};

// Add more methods here
// https://mate.academy/students-api/todos?userId=4060
39 changes: 39 additions & 0 deletions src/components/ErrorNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React, { useEffect } from 'react';
import classNames from 'classnames';

type Props = {
errorMsg: string;
onClose: () => void;
};

export const ErrorNotification: React.FC<Props> = ({ errorMsg, onClose }) => {
useEffect(() => {
if (!errorMsg) {
return;
}

const timerId = setTimeout(() => {
onClose();
}, 3000);

return () => clearTimeout(timerId);
}, [errorMsg, onClose]);

return (
<div
data-cy="ErrorNotification"
className={classNames(
'notification is-danger is-light has-text-weight-normal',
{ hidden: !errorMsg },
)}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={onClose}
/>
{errorMsg}
</div>
);
};
53 changes: 53 additions & 0 deletions src/components/TodoFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React from 'react';
import { Filter } from '../types/Filter';
import classNames from 'classnames';

type Props = {
activeTodos: number;
completedTodos: boolean;
filter: Filter;
onFilterChange: (status: Filter) => void;
onDeleteCompletedTodos: () => void;
};

export const TodoFooter: React.FC<Props> = ({
activeTodos,
completedTodos,
filter,
onFilterChange,
onDeleteCompletedTodos,
}) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodos} items left
</span>

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

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