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

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

develop #1496

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
150 changes: 133 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,142 @@
/* 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 React, { useEffect, useState, useCallback } from 'react';
import { getTodos } from './api/todos';

const USER_ID = 0;
import { Todo } from './types/Todo';
import { ErrorMessages } from './types/ErrorTypes';
import { FilterTypes } from './types/FilterTypes';

import { getVisibleTodos } from './utils/getVisibleTodos';
import { handleError } from './utils/handleError';

import * as todoService from './api/todos';

import { TodoHeader } from './components/TodoHeader';
import { TodoList } from './components/TodoList';
import { TodoFooter } from './components/TodoFooter';
import { ErrorPannel } from './components/ErrorPannel';

export const App: React.FC = () => {
if (!USER_ID) {
return <UserWarning />;
const [todos, setTodos] = useState<Todo[]>([]);
const [tempTodo, setTempTodo] = useState<Todo | null>(null);
const [todosToDelete, setTodosToDelete] = useState<number[]>([]);

const [selectedFilterType, setSelectedFilterType] = useState<FilterTypes>(
FilterTypes.ALL,
);
const [errorMessage, setErrorMessage] = useState<ErrorMessages>(
ErrorMessages.NONE,
);

function handleUpload() {
getTodos()
.then(setTodos)
.catch(() => handleError(setErrorMessage, ErrorMessages.LOAD_FAIL));
}

const filteredTodos = getVisibleTodos(todos, selectedFilterType);
const activeTodosCount = todos.filter(todo => !todo.completed).length;
const completedIds = todos
.filter(todo => todo.completed)
.map(todo => todo.id);

function handleClearCompleted() {
setTodosToDelete(completedIds);
}

const deleteTodos = useCallback(
(idsToDelete: number[]) => {
Promise.allSettled(
idsToDelete.map(id => {
todoService
.deleteTodo(id)
.then(() => {
setTodos(prevTodos => prevTodos.filter(todo => todo.id !== id));
setTodosToDelete(() => []);
})
.catch(() => {
setTodos(todos);
handleError(setErrorMessage, ErrorMessages.DELETE_FAIL);
setTodosToDelete(() => []);
});
}),
);
},
[setTodos, setTodosToDelete, setErrorMessage, todos],
);

function addTodo({ title, userId, completed }: Todo) {
return todoService
.addTodo({ title, userId, completed })
.then(newTodo => {
setTodos([...todos, newTodo]);
setTempTodo(null);
})
.catch(error => {
setTempTodo(null);
handleError(setErrorMessage, ErrorMessages.ADD_FAIL);

throw error;
});
}

const updateTodo = useCallback((todo: Todo) => {
return todoService
.updateTodo(todo.id, todo)
.then(updatedTodo => {
setTodos(current =>
current.map(currentTodo =>
currentTodo.id === updatedTodo.id ? updatedTodo : currentTodo,
),
);
})
.catch(error => {
handleError(setErrorMessage, ErrorMessages.UPDATE_FAIL);
throw error;
});
}, []);

useEffect(handleUpload, [todosToDelete.length]);

useEffect(() => {
if (todosToDelete.length > 0) {
deleteTodos(todosToDelete);
}
}, [deleteTodos, todosToDelete]);

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
onTempTodo={setTempTodo}
onErrorMessage={setErrorMessage}
onAdd={addTodo}
onUpdate={updateTodo}
todos={todos}
/>
{!!todos.length && (
<>
<TodoList
onTodosToDelete={setTodosToDelete}
todos={filteredTodos}
todosToDelete={todosToDelete}
tempTodo={tempTodo}
onUpdate={updateTodo}
/>
<TodoFooter
onSelectedFilterType={setSelectedFilterType}
selectedFilterType={selectedFilterType}
activeTodosCount={activeTodosCount}
completedTodosIds={completedIds}
clearCompletedTodos={handleClearCompleted}
/>
</>
)}
</div>
<ErrorPannel errorMessage={errorMessage} />
</div>
);
};
15 changes: 0 additions & 15 deletions src/UserWarning.tsx

This file was deleted.

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 = 1633;

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

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

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

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

interface Props {
errorMessage: ErrorMessages;
}

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

interface Props {
onSelectedFilterType: (type: FilterTypes) => void;
clearCompletedTodos: () => void;
selectedFilterType: FilterTypes;
activeTodosCount: number;
completedTodosIds: number[];
}

export const TodoFooter: React.FC<Props> = ({

Choose a reason for hiding this comment

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

Suggested change
export const TodoFooter: React.FC<Props> = ({
export const TodoFooter: FC<Props> = ({

clearCompletedTodos,
onSelectedFilterType,
selectedFilterType,
activeTodosCount,
completedTodosIds,
}) => {
return (
<footer className="todoapp__footer" data-cy="Footer">
<span className="todo-count" data-cy="TodosCounter">
{activeTodosCount} items left
</span>

<nav className="filter" data-cy="Filter">
{Object.values(FilterTypes).map(value => (
<a
key={value}
href={value === FilterTypes.ALL ? `#/` : `#/${value.toLowerCase()}`}
className={cn('filter__link', {
selected: selectedFilterType === value,
})}
data-cy={`FilterLink${value}`}
onClick={() => onSelectedFilterType(value)}
>
{value}
</a>
))}
</nav>

<button
type="button"
className="todoapp__clear-completed"
data-cy="ClearCompletedButton"
disabled={!completedTodosIds.length}
onClick={clearCompletedTodos}
>
Clear completed
</button>
</footer>
);
};
113 changes: 113 additions & 0 deletions src/components/TodoHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { useEffect, useRef, useState } from 'react';
import cn from 'classnames';
import { USER_ID } from '../api/todos';

import { ErrorMessages } from '../types/ErrorTypes';
import { Todo } from '../types/Todo';

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

interface Props {
onTempTodo: (todo: Todo | null) => void;
onErrorMessage: (type: ErrorMessages) => void;
onAdd: (todo: Todo) => Promise<void>;
onUpdate: (todos: Todo) => Promise<void>;
todos: Todo[];
}

export const TodoHeader: React.FC<Props> = ({
todos,
onAdd,
onUpdate,
onErrorMessage,
onTempTodo,
}) => {
const [title, setTitle] = useState('');
const [isSubmiting, setIsSubmiting] = useState(false);

const isAllCompleted =
todos.every(todo => todo.completed) && todos.length !== 0;

const todoInput = useRef<HTMLInputElement>(null);

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

if (!title) {
handleError(onErrorMessage, ErrorMessages.EMPTY_TITLE);
setIsSubmiting(false);

return;
}

const tempTodo = {
id: 0,
userId: USER_ID,
title: title.trim(),
completed: false,
};

onTempTodo(tempTodo);
onErrorMessage(ErrorMessages.NONE);

onAdd(tempTodo)
.then(() => {
setTitle('');
})
.catch(() => {
handleError(onErrorMessage, ErrorMessages.ADD_FAIL);
onTempTodo(null);
})
.finally(() => {
onTempTodo(null);
setIsSubmiting(false);
});
};

const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value.trimStart());
onErrorMessage(ErrorMessages.NONE);
};

const handleToggle = () => {
if (isAllCompleted) {
todos.map(todo => onUpdate({ ...todo, completed: false }));
} else {
todos
.filter(todo => !todo.completed)
.map(todo => onUpdate({ ...todo, completed: true }));
}
};

useEffect(() => {
todoInput.current?.focus();
}, [title, isSubmiting, todos.length]);

return (
<header className="todoapp__header">
{!!todos.length && (
<button
type="button"
className={cn('todoapp__toggle-all ', { active: isAllCompleted })}
data-cy="ToggleAllButton"
onClick={handleToggle}
/>
)}

<form onSubmit={handleSubmit}>
<input
data-cy="NewTodoField"
type="text"
className="todoapp__new-todo"
placeholder="What needs to be done?"
value={title}
onChange={handleInput}
autoFocus
disabled={isSubmiting}
ref={todoInput}
/>
</form>
</header>
);
};
Loading
Loading