Reputation: 314
I am having a couple of issues with my Formik Form.
If I use defaultValue={location.fname}
on the <TextField>
I can type in the field,
but on submit the newly typed values do not appear in the alert.
If I use value={location.fname}
on the <TextField>
I can't type in the field.
What am I doing wrong? I would like to be able to type into the field to update the value AND get the new value onSubmit.
let formik = useFormik({
initialValues: {
fname: person.fname,
lname: person.lname,
address: person.address,
city: person.city,
},
enableReinitialize:true,
validateOnChange: false,
validateOnBlur: false,
validationSchema: validationSchema,
onSubmit: values => {
alert(JSON.stringify(values, null, 2));
},
});
...
<TextField
id="fname"
name="fname"
variant="outlined"
defaultValue={location.fname}
onChange={formik.setFieldValue}
error={formik.touched.fname && Boolean(formik.errors.fname)}
helperText={formik.touched.fname && formik.errors.fname} />
Upvotes: 0
Views: 1466
Reputation: 26
Change the defaultValue from location.fname to formik.values.fname as you are already passing the values to formik using initialValues. Also change the onChange from formik.setFieldValue to formik.handleChange and let formik handle the form state through the input name, finally add onBlur={formik.handleBlur} so that formik can know when your input field is touched.
Upvotes: 1