jbreslow
jbreslow

Reputation: 314

Formik initialValues and onSubmit issues

I am having a couple of issues with my Formik Form.

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

Answers (1)

NelsonMK
NelsonMK

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

Related Questions