Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

How to handle with input errors on child components inside the Form? #333

Open
davidtmiranda opened this issue Dec 23, 2020 · 0 comments
Open

Comments

@davidtmiranda
Copy link

I'm using reactjs and the lib unform to handle the register form structure of my application. I needed to do a more complex structure with a dinamic input, then, i did a saparated component to make the code more organized, but when i did the validation with yup i noticed that the fields of the child component didn't receive the errors like i thought it would receive.

Result: just the field of the main component where have the Form component from unform have the validation error.

See the image

here the code of the main form structure:

const CadastroAdvF3: React.FC = () => {

  const { addToast } = useToast();

  const formRef = useRef<FormHandles>(null);

  const handleSubmit = useCallback(
    async data => {

      formRef.current?.setErrors({});

      try {

       // validation

        const schema = Yup.object().shape({
          professionalDescription: Yup.string()
            .required('Descrição profissional obrigatória')
            .min(
              300,
              'A descrição profissional deve ter no mínimo 300 caracteres.'
            ),

          // the following itens are inside the react component formationArea
          // and professionalExperience.

          institution: Yup.string().required('Instituição Obrigatória'),
          course: Yup.string().required('Curso Obrigatório'),
          from: Yup.string().required('Data Obrigatória'),
          until: Yup.string().required('Data Obrigatória'),
          role: Yup.string().required('Cargo Obrigatório'),
          business: Yup.string().required('Empresa/Instituição Obrigatória')
        });

        await schema.validate(data, {
          abortEarly: false
        });

        addToast({
          title: 'Informações registradas com sucesso.',
          type: 'success'
        });
      } catch (error) {
        const errors = getValidationErrors(error);
        formRef.current?.setErrors(errors);
      }
    },
    [addToast]
  );

  return (
    <Styled.Container>
      
      <Styled.Content>
        <Styled.Form>
          <h3>Formulário</h3>

          <Form
            ref={formRef}
            onSubmit={data => {
              handleSubmit(data);
            }}
          >
      
            <TextArea
              name="professionalDescription"
              label="Descrição Profissional"
              placeholder="Sua descrição profissional..."
            />


            <FormationArea />

            <ProfessionalExperience />

            <SuperButton type="submit">Próximo</SuperButton>
          </Form>
        </Styled.Form>
      </Styled.Content>
    </Styled.Container>
  );
};

export default CadastroAdvF3;

And a example of the structure of the FormationArea component:

const FormationArea: React.FC = () => {

  // ...

  return (
    <context.Provider value={{ handleRemoveFormationArea }}>
      <Styled.Container>
        <div className="header">
          <h3>Formação</h3>
          <button type="button" onClick={handleAddFormationArea}>
            Adicionar Instituição
          </button>
        </div>
        {formationAreaFields.map((formationAreaFields, index) => {
          return <Item key={index} Pkey={index} />;
        })}
      </Styled.Container>
    </context.Provider>
  );
};

 // above the component that is rendered in the formation area

const Item: React.FC<KeyComponentProp> = ({ Pkey }) => {

 // ....

  return (
    <CourseAreasContext.Provider
      value={{ handleRemoveCourseArea, handleAddCourseArea }}
    >
      <div className="item">
        <Scope path={`formation[${Pkey}]`}>
          {/* <h4>Instituição</h4> */}
          <Styled.PersonalizedColumnsFormation>
            <Input
              label="Instituição"
              name="institution"
              placeholder="Instituição"
            />
            {Pkey > 0 && (
              <button
                type="button"
                onClick={() => handleRemoveFormationArea(Pkey)}
              >
                <TiTrash size={23} />
              </button>
            )}
          </Styled.PersonalizedColumnsFormation>
          {CourseAreaFields.map((course, index) => {
            return <DownScopeAreas key={index} Pkey={index} />;
          })}
        </Scope>
      </div>
    </CourseAreasContext.Provider>
  );
};

export default FormationArea;

@davidtmiranda davidtmiranda changed the title How to handle with input errors on child components? How to handle with input errors on child components inside the Form? Dec 23, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant