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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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 @@ -41,4 +41,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://andrmar1939.github.io/react_todo-app-with-api/) and add it to the PR description.
20 changes: 8 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
/* eslint-disable max-len */
/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import { UserWarning } from './UserWarning';

const USER_ID = 0;
import { AppProvider } from './Context';
import USER_ID from './helpers/USER_ID';

import { UserWarning } from './Pages/NotAuth/UserWarning';
import { Application } from './Pages/Application/Application';

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>
<AppProvider>
<Application />
</AppProvider>
);
};
102 changes: 102 additions & 0 deletions src/Components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import React from 'react';
import cn from 'classnames';

import { FiltersType } from '../../types/filterTypes';
import { useApiErrorContext, useFormFocusContext, useTodosContext }
from '../../hooks/getContextHooks';
import { deleteTodo } from '../../api/todos';
import {
deleteTodoAction,
setIsSpinningAction,
removeIsSpinningAction,
} from '../../Context/actions/actionCreators';

import { getActiveTodos, getCompletedTodos }
from '../../helpers/getFilteredTodos';

export const Footer: React.FC = () => {
const { setIsFocused } = useFormFocusContext();
const {
todos,
filter,
setFilter,
dispatch,
} = useTodosContext();
const { setApiError } = useApiErrorContext();

const activeTodosNumber = getActiveTodos(todos).length;
const completedTodos = getCompletedTodos(todos);
const isClearCompletedInvisible = completedTodos.length === 0;

Choose a reason for hiding this comment

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

Suggested change
const isClearCompletedInvisible = completedTodos.length === 0;
const isClearCompletedInvisible = !completedTodos.length;


const handleClearCompletedClick = () => {
setIsFocused(false);

const deletedTodos = completedTodos.map(({ id }) => {
const isSpinningAction = setIsSpinningAction(id);

dispatch(isSpinningAction);

return deleteTodo(id)
.then(() => {
const deleteAction = deleteTodoAction(id);

dispatch(deleteAction);
})
.catch((error) => {
const removeAction = removeIsSpinningAction(id);

dispatch(removeAction);
setApiError(error);
})
.finally(() => {
setIsFocused(true);
});
});

return deletedTodos;
};

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

Choose a reason for hiding this comment

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

If there is one item, there should not be a plural in the text.

</span>

<nav className="filter" data-cy="Filter">
{(Object.entries(FiltersType))
.map(([key, value]) => {
const url = value === FiltersType.ALL
? ''
: value.toLowerCase();

Choose a reason for hiding this comment

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

You can change the FiltersType a little and then you won't need to add an extra check:

export enum FiltersType {
  ALL = '',
  ACTIVE = 'Active',
  COMPLETED = 'Completed',
}
...
const url = value.toLowerCase();

Copy link
Author

Choose a reason for hiding this comment

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

Brilliant!


return (
<a
data-cy={`FilterLink${value}`}
href={`#/${url}`}
key={key}
className={cn('filter__link', {
selected: filter === value,
})}
onClick={() => setFilter(value)}
>
{value}
</a>
);
})}
</nav>

<button
data-cy="ClearCompletedButton"
type="button"
className={cn('todoapp__clear-completed', {
'is-invisible': isClearCompletedInvisible,
})}
onClick={handleClearCompletedClick}
disabled={isClearCompletedInvisible}
>
Clear completed
</button>

</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 * from './Footer';
33 changes: 33 additions & 0 deletions src/Components/Form/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from 'react';

type Props = {
placeholder: string,
onInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void,
value: string,
onSubmit: (e: React.FormEvent<HTMLFormElement>) => void,
forCypress: string,
className: string,
onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void,
onKeyUp?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
};

type Ref = HTMLInputElement | null;

export const Form = React.forwardRef<Ref, Props>(({
placeholder,
onInputChange,
onSubmit,
forCypress,
...props
}, ref) => (
<form onSubmit={onSubmit}>
<input
data-cy={forCypress}
type="text"
placeholder={placeholder}
onChange={onInputChange}
ref={ref}
{...props}
/>
</form>
));
1 change: 1 addition & 0 deletions src/Components/Form/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Form';
154 changes: 154 additions & 0 deletions src/Components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import React, {
useEffect,
useRef,
useState,
} from 'react';
import cn from 'classnames';

import { useApiErrorContext, useFormFocusContext, useTodosContext }
from '../../hooks/getContextHooks';
import { Form } from '../Form';
import USER_ID from '../../helpers/USER_ID';
import { addTodo, patchTodo } from '../../api/todos';
import {
postTodoAction,
removeIsSpinningAction,
setIsSpinningAction,
patchTodoAction,
} from '../../Context/actions/actionCreators';
import { emptyInputError } from '../../types/apiErrorsType';
import { getActiveTodos } from '../../helpers/getFilteredTodos';

export const Header: React.FC = () => {
const { todos, setTempTodo, dispatch } = useTodosContext();
const { isFocused } = useFormFocusContext();
const { setApiError } = useApiErrorContext();
const ref = useRef<HTMLInputElement>(null);
const [inputValue, setInputValue] = useState('');

const isToggleVisible = todos.length > 0;

Choose a reason for hiding this comment

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

Suggested change
const isToggleVisible = todos.length > 0;
const isToggleVisible = !!todos.length;

const isToggleActive = todos.every(todo => todo.completed);

useEffect(() => {
if (ref.current && isFocused) {
ref.current.focus();
}
}, [ref, isFocused]);

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const preparedInputValue = inputValue.trim();

if (!preparedInputValue.length) {
setApiError(new Error(emptyInputError));

return;
}

const data = {
userId: USER_ID,
title: preparedInputValue,
completed: false,
};

setTempTodo({ ...data, isSpinned: true, id: 0 });

if (ref.current) {
ref.current.blur();
ref.current.disabled = true;
}

addTodo(data)
.then((newTodo) => {
const actionPost = postTodoAction(newTodo);

dispatch(actionPost);
setInputValue('');
})
.catch(error => setApiError(error))
.finally(() => {
setTempTodo(null);

if (ref.current && isFocused) {
ref.current.disabled = false;
ref.current.focus();
}
});
};

const handleAllToggle = () => {
const todosForToggle = isToggleActive
? todos
: getActiveTodos(todos);

const toggledTodos = todosForToggle.map(({ id }) => {
const isSpinningAction = setIsSpinningAction(id);
const data = { completed: !isToggleActive };

dispatch(isSpinningAction);

return patchTodo(id, data);
});

Promise.allSettled(toggledTodos);

/* eslint-disable @typescript-eslint/no-explicit-any */
Promise.allSettled(toggledTodos)
.then((data: any) => {
Comment on lines +97 to +99

Choose a reason for hiding this comment

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

🔥
If you are interested you can google how to handle type for Promise.allSettled
https://stackoverflow.com/questions/64928212/how-to-use-promise-allsettled-with-typescript

const fulfilled = data.filter((promise: any) => promise?.value);
const rejected = data.filter((promise: any) => promise?.reason);

fulfilled.forEach((promise: any) => {
const todo = promise.value;
const patchAction = patchTodoAction(todo);
const removeAction = removeIsSpinningAction(todo.id);

dispatch(removeAction);
dispatch(patchAction);
});

if (rejected.length > 0) {

Choose a reason for hiding this comment

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

Suggested change
if (rejected.length > 0) {
if (rejected.length) {

setApiError(rejected[0].reason);

todosForToggle.forEach(({ id }) => {
const removeAction = removeIsSpinningAction(id);

dispatch(removeAction);
});
}
})
.catch((error) => {
setApiError(error);
});
};

return (
<header className="todoapp__header">
{/* eslint-disable jsx-a11y/control-has-associated-label */}

Choose a reason for hiding this comment

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

Try to rewrite the code so that it is not necessary to disable the linter

{isToggleVisible && (
<button
type="button"
className={cn('todoapp__toggle-all', {
active: isToggleActive,
})}
data-cy="ToggleAllButton"
onClick={handleAllToggle}
/>
)}

<Form
forCypress="NewTodoField"
ref={ref}
placeholder="What needs to be done?"
className="todoapp__new-todo"
onInputChange={handleInputChange}
value={inputValue}
onSubmit={handleSubmit}
/>
</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 * from './Header';
Loading