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

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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.
21 changes: 9 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
/* 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 { TodosProvider } from './Context';
import USER_ID from './helpers/USER_ID';

// components
import { UserWarning } from './Pages/Auth/UserWarning';

Choose a reason for hiding this comment

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

Remove comments

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

import { FiltersType } from '../../types/filterTypes';
import { TodosContext, ApiErrorContext, FormFocusContext } from '../../Context';
import { deleteTodo } from '../../api/todos';
import {
deleteTodoAction,
setIsSpinningAction,
removeIsSpinningAction,
} from '../../Context/actions/actionCreators';

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

export const Footer: React.FC = () => {
const { setIsFocused } = useContext(FormFocusContext);
const {
todos,
filter,
setFilter,
dispatch,
} = useContext(TodosContext);
const { setApiError } = useContext(ApiErrorContext);
Comment on lines +16 to +23

Choose a reason for hiding this comment

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

Create hooks for your contexts, so you don't need to pass a context every time.
As example:

const useTodos = () => useContext(TodosContext);


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

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

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

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

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

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

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

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

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';
39 changes: 39 additions & 0 deletions src/Components/Form/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
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,
value,
onSubmit,
forCypress,
className,
onBlur = () => {},
onKeyUp = () => {},
}, ref) => (
<form onSubmit={onSubmit}>
<input
data-cy={forCypress}
type="text"
className={className}
placeholder={placeholder}
onChange={onInputChange}
ref={ref}
value={value}
onBlur={onBlur}
onKeyUp={onKeyUp}
/>

Choose a reason for hiding this comment

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

Hint:

  • if you don't need at this level props and just want to pass them to the next component you can use the spread syntax. Example:
function Profile(props) {
  return (
    <div className="card">
      <Avatar {...props} />
    </div>
  );
}

https://react.dev/learn/passing-props-to-a-component

  • also, in this case, you can reuse props type

In your case get onSubmit from props and pass other props to the next component

</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';
141 changes: 141 additions & 0 deletions src/Components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import React, {
useContext,
useEffect,
useRef,
useState,
} from 'react';
import cn from 'classnames';

import { TodosContext, ApiErrorContext, FormFocusContext } from '../../Context';
import { Form } from '../Form';
import USER_ID from '../../helpers/USER_ID';
import { addTodo, patchTodo } from '../../api/todos';
import {
postTodoAction,
removeIsSpinningAction,
patchTodoAction,
setIsSpinningAction,
} from '../../Context/actions/actionCreators';
import { emptyInputError } from '../../types/apiErrorsType';
import { getActiveTodos } from '../../helpers/getTodos';

// Component

Choose a reason for hiding this comment

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

Don't leave redundant comments, remove all of them

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

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

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

// handlers

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

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

dispatch(isSpinningAction);

patchTodo(id, data)
.then((patchedTodo) => {
Comment on lines +94 to +95

Choose a reason for hiding this comment

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

Don't do async operations in forEach. You can use await in for of loop or even better with map collect all your requests and use Promise.all

const patchAction = patchTodoAction(patchedTodo);

dispatch(patchAction);
})
.catch((error) => {
setApiError(error);
})
.finally(() => {
const removeAction = removeIsSpinningAction(id);

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

// render

return (
<header className="todoapp__header">
{/* eslint-disable jsx-a11y/control-has-associated-label */}
{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
Loading