1

I send pieces of code that involve a field array in formik, the issue is the following: on the one hand the buttons to add and delete fields work correctly, on the other hand the text boxes they work since you can enter data in them but when the form is submitted, this data entered in the text boxes contained in a fieldarray is not sent, thanks for now.

Initial values of the form


  const formik = useFormik({
        initialValues: {
            no_doc: '',
            apellido: '',
            nombre: '',
            fec_nac: '',
            sexo: '',
            domicilio: '',
            no_tel: '',
            email: '',
            obra_soc: '',
            no_obra_soc: '',
            plan_obra_soc: '',
            fec_prot: Date.now.toString(),
            medico: '',
            diagnostico: '',
            medicacion: '',
            practicas_solicitadas: '',
            practica_s: [
                {
                cod_ana: '',
                autorizada: '',
                obra_soc:''
            }]
        },
       
        onSubmit: (data) => {
           // setFormData(data);
            setShowMessage(true);
            console.log(data);
            formik.resetForm();
        }

    });

Formik FieldArray code



 <FormikProvider value={formik}>
    <FieldArray name='practica_s'>
       {({push, remove, Formik }) => (
          <React.Fragment>
              {formik.values.practica_s.map(( practica_s , index) => (
                   <Grid container item>
                       <Grid item>
                            <Field name={`practica_s[${index}].cod_ana`}
                                   id="practica_s.cod_ana"
                                   component= {Autocomplete}
                                   sx={{ width: 300 }}
                                   autoHighlight    
                                   value= {practicas.cod_ana}
                                   options={practicas}        
                                   getOptionLabel={(option) => option.nom_ana}
                                   renderInput={(params) => <TextField {...params} label="Practica" />}/>
                        </Grid>
                             <Grid item>
                                 <Field name={`practica_s[${index}].autorizada`} 
                                 id="autorizada"
                                 component= {TextField}
                                 label= "Autorizada ?" />
                             </Grid>
                            <Grid item>
                                <Field name={`practica_s[${index}].obra_soc`} 
                                       id="obra_soc"
                                       component= {TextField}
                                       label= "Obra Social" />
                         </Grid>
                             <Grid item>
                                <Button  onClick={() => remove(index)}>Delete</Button>
                             </Grid>
                         </Grid>
             ))}
                            <Grid item>
                                <Button type='button' onClick={() => push({cod_ana:'', autorizacion:'', obra_soc:''})}>Add</Button>
                            </Grid>
        </React.Fragment>
    )}
  </FieldArray>
</FormikProvider>

4
  • I build a CodeSandBox with your code and I think the problem is with the components you're passing to the Field property. Just by commenting those, it works fine. Can you post the code from your <TextField/> component? CodeSandBox link => codesandbox.io/s/determined-meitner-hpo1q?file=/src/App.js Commented Jan 31, 2022 at 19:53
  • Also, noticed you're missing the key in <Grid container item> after the .map(). Try adding that one too. Commented Jan 31, 2022 at 21:00
  • Yes, the problem is definitely in the submitted component, I have already understood how to deal with simple elements like input text, now I should understand how to work with autocomplete fields and pass the data to the formik form, I think the key is in the renderInput option Any ideas? Thanks again. Commented Feb 1, 2022 at 2:26
  • Easy. You can use useFormikContext() and useField() to create your own custom fields. I updated the CodeSand box, with a custom Searchable component. Using react-select. Check it out, and let me know if I can help you. Commented Feb 1, 2022 at 5:10

1 Answer 1

1

Finally, thanks to the help of @Thremulant, I was able to reformulate the "Fieldarray code" so that everything works. Basically, at the Field the "component" option has been changed to the "as" option. On the other hand I rewrote the code of the "Autocomplete" field so that when the selection is changed, a different value can be passed to the "Field" of FieldArray than the one that the select shows, I await comments and thanks in advance for the help provided


<FormikProvider value={formik}>
  <FieldArray name='practica_s'>
    {({push, remove, Formik }) => (
      <React.Fragment>
        {formik.values.practica_s.map(( practica_s , index) => (
        <>
          <div className="p-col-12 p-md-3">
            <Autocomplete
              id="practicas"
              name="practicas"
              options={practicas}
              getOptionLabel={option => option.nom_ana}
              onChange={(e, value) => {
                formik.setFieldValue(`practica_s[${index}].cod_ana` , value.cod_ana)
                }}
              renderInput={params => (<TextField {...params}
                              name={`practica_s[${index}].autorizada`}  
                              label="Prtacticas"
                              variant="outlined"
                               />
              )}
              />
              </div>
              <div className="p-col-12 p-md-3">
                <div className="p-inputgroup">
                    <Field name={`practica_s[${index}].autorizada`} 
                       id="autorizada"
                       as= {InputText}
                       label= "Autorizada ?" />
                 </div>
               </div>
               <div className="p-col-12 p-md-3">
                 <div className="p-inputgroup">
                     <Field name={`practica_s[${index}].obra_soc`} 
                         id="obra_soc"
                         as= {InputText}
                         label= "Obra Social" />
                  </div>
                </div>
                <div className="p-col-12 p-md-3">
                    <Button  onClick={() => remove(index)}>Delete</Button>
                 </div>
      </>
     ))}
        <div className="p-col-12 ">
          <Button type='button' onClick={() => push({cod_ana:'', autorizada:'', obra_soc:''})}>Add</Button>
         </div>
   </React.Fragment>
   )}
 </FieldArray>
</FormikProvider>

Sign up to request clarification or add additional context in comments.

1 Comment

Did you manage to set a default value to the autocomplete?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.