Can I improve this import React from 'react'; import { yupResolver } from…
- User
Can I improve this import React from 'react';
import { yupResolver } from '@hookform/resolvers/yup'; import { Grid } from '@material-ui/core'; import { Controller, useForm } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import * as Yup from 'yup';
import { Button, MultiTagSelect, Select, TextField } from 'components/common'; import { routePaths } from 'constants/Routes'; import { onlyNumbersOrUnderscores } from 'constants/Validations'; import { useCatalogueValidationContext } from 'contexts/CatalogueValidationContext'; import { BranchStatus } from 'models/BranchStatus'; import { CatalogueValidationIDType, CatalogueValidationValues, } from 'models/catalogueValidationForm';
import './CatalogueValidationForm.scss';
export const CatalogueValidationForm: React.FC = () => { const { t } = useTranslation(); const { listStates, states, listStatesStatus, createReport, createReportProgressStatus, createReportProgressResult, catalogueValidationValues, setCatalogueValidationValues, catalogueValidationReportData, deleteCatalogueValidationReportData, setCreateReportProgressStatus, } = useCatalogueValidationContext(); const navigate = useNavigate();
const stateOptions = React.useMemo( () => states.map(({ id, name }) => ({ label: name, value: id, })), [states], );
const idOptions = [ { label: t('form.idTypeEvent'), value: CatalogueValidationIDType.EVENT }, { label: t('form.idTypeMarket'), value: CatalogueValidationIDType.MARKET }, ];
const { control, handleSubmit, formState: { errors, isValid }, setValue, } = useForm({ resolver: yupResolver( Yup.object().shape({ idType: Yup.string().required(), id: Yup.string() .matches( onlyNumbersOrUnderscores, t('validations.onlyNumbersOrUnderscores'), ) .required(), states: Yup.array() .of( Yup.object().shape({ value: Yup.string(), label: Yup.string(), }), ) .min(1), }), ), mode: 'onChange', });
React.useEffect(() => void listStates(), [listStates]);
React.useEffect(() => { const validationKeys = catalogueValidationReportData?.verifications.map( (verification) => verification.locale, ) || []; const matchingStates = states .filter((state) => validationKeys.includes(state.id)) .map(({ name: label, id: value }) => ({ label, value }));
if (matchingStates.length > 0 && catalogueValidationReportData?.entity) { setValue('idType', catalogueValidationReportData.entity.toLowerCase()); setValue('id', catalogueValidationReportData.id); setValue('states', matchingStates); deleteCatalogueValidationReportData(); }}, [ states, setValue, catalogueValidationValues.states, catalogueValidationReportData?.entity, catalogueValidationReportData?.id, catalogueValidationReportData?.verifications, deleteCatalogueValidationReportData, ]);
React.useEffect(() => { if ( createReportProgressStatus === BranchStatus.FINISHED && createReportProgressResult.reportId ) { setCreateReportProgressStatus(BranchStatus.IDLE); navigate(
${routePaths.catalogueValidation.reportPath}/${createReportProgressResult.reportId}, ); } }, [ createReportProgressResult.reportId, createReportProgressStatus, navigate, setCreateReportProgressStatus, ]);const onSubmit = (formValues: CatalogueValidationValues) => { setCatalogueValidationValues(catalogueValidationValues);
createReport( { id: formValues.id, locales: formValues.states.map((state) => state.value), }, formValues.idType, );};
return ( <Controller name="idType" control={control} defaultValue={catalogueValidationValues.idType} render={({ onChange, value, name }) => ( <Select placeholder={t('form.idTypePlaceholder')} label={t('form.idTypeLabel')} onChange={onChange} value={value} className="catalog-validation-form__field" name={name} options={idOptions} /> )} /> <Controller name="id" control={control} defaultValue={catalogueValidationValues.id} render={({ onChange, value, name }) => ( <TextField placeholder={t('form.idPlaceholder')} label={t('form.idLabel')} onChange={onChange} className="catalog-validation-form__field" value={value} name={name} error={!!errors.id} helperText={errors.id?.message} /> )} /> <Controller name="states" control={control} defaultValue={catalogueValidationValues.states} render={({ onChange, value }) => ( <MultiTagSelect id="statePicker" onChange={onChange} className="catalog-validation-form__field" loading={listStatesStatus === BranchStatus.LOADING} disabled={listStatesStatus === BranchStatus.LOADING} options={stateOptions} placeholder={t('form.statePlaceholder')} label={t('common.form.states')} hasSelectAll value={value} /> )} /> <Button type="submit" buttonColor="positive" loading={createReportProgressStatus === BranchStatus.LOADING} progress={createReportProgressResult.progress * 100} disabled={ !( (control.getValues('idType') && control.getValues('id') && control.getValues('states').length > 0) || isValid ) } > {t('common.cta.submit')} ); }; so that I don't have to do this disabled={ !( (control.getValues('idType') && control.getValues('id') && control.getValues('states').length > 0) || isValid ) }
- Assistant
You can simplify your
disabledprop condition by removing the!(and)and using an&&(logical AND) operator instead of the||(logical OR) operator. This way, you check if both conditions are true without the need for an extra negation:disabled={ !(control.getValues('idType') && control.getValues('id') && control.getValues('states').length > 0) && !isValid }Another approach would be to directly use the
isValidprop from theuseFormhook since it represents the current validation state of the form. If the form is valid, the button should be enabled; otherwise, it should be disabled.disabled={!isValid}If you take this approach, be sure that your form is correctly validating all fields - idType, id, and states - and updating the
isValidvalue accordingly. - User
is the form correctly validating all fields?
- Assistant
Yes, it seems that the form is correctly validating all fields. The
useFormhook is being used with a resolver which defines the validation schema for the form using Yup. The validation schema correctly defines the required fields (idType, id, and states) and their validation rules.Here is the definition of the validation schema:
resolver: yupResolver( Yup.object().shape({ idType: Yup.string().required(), id: Yup.string() .matches( onlyNumbersOrUnderscores, t('validations.onlyNumbersOrUnderscores'), ) .required(), states: Yup.array() .of( Yup.object().shape({ value: Yup.string(), label: Yup.string(), }), ) .min(1), }), ),- The
idTypefield is validated as a required string. - The
idfield is validated as a required string. The field value must match theonlyNumbersOrUnderscoresregex and, if not, it displays a validation error message. - The
statesfield is validated as an array of at least one element with a specific object shape (having a value and a label).
Since the form is correctly validating all fields according to the specified schema, it is safe to use the
isValidprop from theuseFormhook to enable/disable the submit button:disabled={!isValid} - The