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

Develop #1480

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Develop #1480

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
122 changes: 103 additions & 19 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,110 @@
/* 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';
import { FC, useEffect, useMemo, useState } from 'react';

const USER_ID = 0;
import { Todo } from './types/Todo';
import { Errors } from './types/Errors';
import { FilterBy } from './types/FilterBy';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
}
import { getFilteredTodos } from './utils/getFilteredTodos';
import { handleFetchTodos } from './utils/handleFetchTodos';
import { handleDeleteTodos } from './utils/handleDeleteTodos';

import { Header, TodoList, Footer, ErrorMessage, TodoItem } from './components';
import { handleUpdateTodos } from './utils/handleUpdateTodos';

export const App: FC = () => {
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [newTodoData, setNewTodoData] = useState<Partial<Todo>>({});

const [idsForDelete, setIdsForDelete] = useState<number[]>([]);
const [idsForUpdate, setIdsForUpdate] = useState<number[]>([]);

const [error, setError] = useState<Errors>(Errors.DEFAULT);

const [selectedFilter, setSelectedFilter] = useState<FilterBy>(FilterBy.ALL);

const completedTodosId = useMemo(() => {
return getFilteredTodos(todos, FilterBy.COMPLETED).map(todo => todo.id);
}, [todos]);

const numberOfActiveTodos = useMemo(() => {
return getFilteredTodos(todos, FilterBy.ACTIVE).length;
}, [todos]);

const filteredTodos = useMemo(() => {
return getFilteredTodos(todos, selectedFilter);
}, [todos, selectedFilter]);

useEffect(() => {
if (idsForDelete.length) {
handleDeleteTodos(idsForDelete, setTodos, setIdsForDelete, setError);
}
}, [idsForDelete]);

useEffect(() => {
if (idsForUpdate.length) {
handleUpdateTodos(
idsForUpdate,
newTodoData,
setTodos,
setIdsForUpdate,
setError,
);
}
}, [idsForUpdate, newTodoData]);

useEffect(() => {
handleFetchTodos(setTodos, setError);
}, []);

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
todos={todos}
tempTodo={tempTodo}
numberOfActiveTodos={numberOfActiveTodos}
setTodos={setTodos}
setError={setError}
setTempTodo={setTempTodo}
setIdsForUpdate={setIdsForUpdate}
setNewTodoData={setNewTodoData}
/>

<TodoList
todos={filteredTodos}
idsForDelete={idsForDelete}
idsForUpdate={idsForUpdate}
setIdsForDelete={setIdsForDelete}
setIdsForUpdate={setIdsForUpdate}
setNewTodoData={setNewTodoData}
/>

{tempTodo && (
<TodoItem
todo={tempTodo}
setIdsForDelete={setIdsForDelete}
setIdsForUpdate={setIdsForUpdate}
setNewTodoData={setNewTodoData}
/>
)}

Comment on lines +87 to +94

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it can be put inside TodoList component

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its makes according to part 2 of the todo app
image

{!!todos.length && (
<Footer
selectedFilter={selectedFilter}
completedTodosId={completedTodosId}
numberOfActiveTodos={numberOfActiveTodos}
setSelectedFilter={setSelectedFilter}
setIdsForDelete={setIdsForDelete}
/>
)}
</div>

<ErrorMessage error={error} setError={setError} />
</div>
);
};
24 changes: 24 additions & 0 deletions src/api/todos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Todo } from '../types/Todo';

import { client } from '../utils/fetchClient';

import { USER_ID } from '../constants/constants';

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

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

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

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

import { Errors } from '../../types/Errors';
import { handleError } from '../../utils/handleError';

interface Props {
error: Errors;
setError: (error: Errors) => void;
}

export const ErrorMessage: FC<Props> = ({ error, setError }) => {
const handleClose = () => {
handleError(Errors.DEFAULT, setError);
};

return (
<div
data-cy="ErrorNotification"
className={cn('notification is-danger is-light has-text-weight-normal', {
hidden: !error,
})}
>
<button
data-cy="HideErrorButton"
type="button"
className="delete"
onClick={handleClose}
/>
{error}
</div>
);
};
1 change: 1 addition & 0 deletions src/components/ErrorMessage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ErrorMessage';
58 changes: 58 additions & 0 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { FC } from 'react';
import cn from 'classnames';

import { FilterBy } from '../../types/FilterBy';

interface Props {
selectedFilter: FilterBy;
completedTodosId: number[];
numberOfActiveTodos: number;
setSelectedFilter: (filter: FilterBy) => void;
setIdsForDelete: (ids: number[]) => void;
}

const Footer: FC<Props> = ({
selectedFilter,
completedTodosId,
numberOfActiveTodos,
setSelectedFilter,
setIdsForDelete,
}) => {
const filters = Object.values(FilterBy);

return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{numberOfActiveTodos} items left
</span>

<nav className="filter" data-cy="Filter">
{filters.map(filter => (
<a
key={filter}
href="#/"
className={cn('filter__link', {
selected: filter === selectedFilter,
})}
data-cy={`FilterLink${filter}`}
onClick={() => setSelectedFilter(filter)}
>
{filter}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
onClick={() => setIdsForDelete(completedTodosId)}
disabled={!completedTodosId.length}
>
Clear completed
</button>
</footer>
);
};

export default Footer;
1 change: 1 addition & 0 deletions src/components/Footer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Footer } from './Footer';
116 changes: 116 additions & 0 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { ChangeEvent, FC, FormEvent, useEffect, useRef, useState } from 'react';
import cn from 'classnames';

import { Todo } from '../../types/Todo';
import { Errors } from '../../types/Errors';

import { addTodo } from '../../api/todos';
import { handleError } from '../../utils/handleError';

import { USER_ID } from '../../constants/constants';

interface Props {
todos: Todo[];
tempTodo: Todo | null;
numberOfActiveTodos: number;
setTodos: (updateTodos: (todos: Todo[]) => Todo[]) => void;
setError: (error: Errors) => void;
setTempTodo: (todo: Todo | null) => void;
setIdsForUpdate: (prevIds: (ids: number[]) => number[]) => void;
setNewTodoData: (newData: Partial<Todo>) => void;
}

const Header: FC<Props> = ({
todos,
tempTodo,
numberOfActiveTodos,
setTodos,
setError,
setTempTodo,
setIdsForUpdate,
setNewTodoData,
}) => {
const [title, setTitle] = useState('');
const inputRef = useRef<HTMLInputElement>(null);

const handleChangeTitle = (event: ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value.trimStart());
};

const handleFormSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();

const formattedTitle = title.trim();

if (!formattedTitle) {
handleError(Errors.TITLE_ERROR, setError);

return;
}

const newTodo: Omit<Todo, 'id'> = {
userId: USER_ID,
title: formattedTitle,
completed: false,
};

const tmpTodo: Todo = {
id: 0,
...newTodo,
};

setTempTodo(tmpTodo);

try {
const todo = await addTodo(newTodo);

setTodos(currentTodos => [...currentTodos, todo]);
setTitle('');
setTempTodo(null);
} catch {
setTempTodo(null);
handleError(Errors.ADD_TODO, setError);
}
};

const handleToggleAll = () => {
const isAllTodosCompleted = todos.every(todo => todo.completed);

todos.map(todo => {
setIdsForUpdate(currentIds => [...currentIds, todo.id]);
setNewTodoData({ completed: isAllTodosCompleted ? false : true });
});
};

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

return (
<header className="todoapp__header">
<button
type="button"
className={cn('todoapp__toggle-all', {
active: !numberOfActiveTodos,
})}
data-cy="ToggleAllButton"
onClick={handleToggleAll}
/>

<form onSubmit={handleFormSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
ref={inputRef}
value={title}
onChange={handleChangeTitle}
disabled={!!tempTodo}
/>
</form>
</header>
);
};

export default Header;
1 change: 1 addition & 0 deletions src/components/Header/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Header } from './Header';
Loading
Loading