Skip to content

Refactoring#1

Open
gentslava wants to merge 8 commits into
masterfrom
feature/refactoring
Open

Refactoring#1
gentslava wants to merge 8 commits into
masterfrom
feature/refactoring

Conversation

@gentslava

@gentslava gentslava commented Feb 28, 2024

Copy link
Copy Markdown
Member

Рефакторинг компонента.
История изменений https://github.com/rosstrah/frontend-test/pull/1/commits

@gentslava gentslava changed the title Feature - Refactoring Refactoring Feb 28, 2024

@gentslava gentslava left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Комментарии по ревью

Comment thread index.js

const showError = (internalErrors, errorsServer) => {
useEffect(() => {
if (!errorsServer && !errorsServer.isArray()) return null;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Потенциальная ошибка. Базово в js у объектов нет метода isArray().
Здесь несколько вариантов:

  • Это ошибка и предполагается Array.isArray(errorsServer).
  • Этот метод определен в объекте errorsServer.
  • Этот метод определен через прототипирование.

Нужно понимать, какой у нас случай.
По хорошему, вопросов бы не возникло, если бы errorsServer был подробно типизирован, а не просто errorsServer: PropTypes.array.
Для этих целей нужно подробнее через propTypes расписать поля объекта, либо использовать ts.

Comment thread index.js
} = props;

const showError = (internalErrors, errorsServer) => {
useEffect(() => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Перенес в useEffect, чтобы не было лишних срабатываний на каждый рендер.

Comment thread index.js
sendAgentCard,
// surnameSuggestions,
// firstNameSuggestions,
// patronymicSuggestions,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Комментарии обязательно удаляем. Все есть в git.

Comment thread index.js
</FormRow>
</>
)}
{false && props.username === userInfo.username && (

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Пусть false не смущает. Его убирать не нужно, раз вопросов о нерабочей функциональности не возникала.
Это банально отключённая функциональность = закомментированный код. Не долго думая, удаляем.

Comment thread index.js
}
});
};
}, [internalErrors, errorsServer]);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Вообще в этой функции происходят мутации объектов, что является анти паттерном React. Дочерний компонент мутирует объекты, которые приходят из родительского компонента. Такое сложно отлаживать, если дочерний компонент занесет ошибку.
Учитывая, что здесь просто происходят какие-то пробросы из одних ключей в другие, имеет смысл эти ключи добавить в валидатор, а данную функцию просто выпилить.

Comment thread const.js
whatsappBotEnable: "Подключить бота Whatsapp",
whatsappNotifyDisable: "Отключить уведомления Whatsapp",
whatsappNotifyEnable: "Подключить уведомления Whatsapp",
juridicalError: "Если вы хотите работать как юридическое лицо, то необходимо заключить с нами договор. Для этого вам нужно обратиться в тех. поддержку по телефону +7 (800) 550-50-43, либо написать на почту docs@rosstrah.ru, в теме письма указав свой логин",

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Отображаемый текст выносим по той же причине. Плюс есть потенциал для локализации на разные языки.

Comment thread const.js
verificationPhoneModal: "verificationPhoneModal",
success: "success",
error: "error",
text: "text",

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Константные строки лучше вынести в константы, чтобы сложнее было опечататься в названиях и было проще отладить такого типа ошибки.

value={userInfo.email}
onChange={(value) => setValue([MAGIC_STRINGS.userInfo, MAGIC_STRINGS.email], value)}
onBlur={(value) => {
validate(MAGIC_STRINGS.email, value);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Функции в onChange, onBlur можно вынести в отдельные хендлеры. Тогда компонент будет чище, логика и отображение будут разделены.

@@ -0,0 +1,146 @@
import React, { memo } from "react";
import moment from "moment";

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Библиотека moment.js deprecated. Можно использовать более легковесную библиотеку day.js

Comment thread index.js
if (loading) return (
<EmptyNoBorder>
<Spinner />
</EmptyNoBorder>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

<EmptyNoBorder><Spinner /></EmptyNoBorder>
можно вынести в отдельный компонент <Loader />, который будет в UI-kit проекта.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant