简体   繁体   中英

React using Formik does not clear the data value in Material UI form

I'm using formik.resetForm() to remove values from text fields in a form after submitting the data.

...
  const handleSubmitProduct = async (values: Object, resetForm: any) => {

    ... code to handle my form data ... 

    resetForm()

    if (response.ok) {
      console.debug(response.status)
    } else {
      console.error(response)
    }
  }

  const validate = (values: Object) => {
    const errors: any = {}

    if (!values.product_name) {
      errors.product_name = "Include name"
    } 
    return errors 
  }

  ... initialValues defined ...  

  const formik = useFormik({
    initialValues: initialValues,
    validate,
    onSubmit: (values: Object, { resetForm }) => {
      console.debug(JSON.stringify(values, null, 2))
      handleSubmitProduct(values, resetForm)
    },
  })

  return (
    <FormLabel>Display name</FormLabel>
     <TextField
       onChange={formik.handleChange}
       id="product_name"
       onBlur={formik.handleBlur}
       error={formik.touched.product_name && Boolean(formik.errors.product_name)}
       helperText={formik.touched.product_name && formik.errors.product_name}
     />
    <Button onClick={() => formik.handleSubmit()} variant="contained">
      Submit  
    </Button>
  )

I know there are many other questions like this but mine is different where I know the underlying Formik resources for values, errors, touched have been cleared but the values are still present in the text boxes.

The issue is I know the underlying Formik objects are cleared because after I submit, the validation triggers and prompts me like there is no value in the text field.

I've tried

  • resetForm({values: {initialValues}}) has the same result
  • resetForm(initialValues) has the same result
  • Use action.resetForm({values: {initialValues}}) in the onSubmit() which same result
  • https://codesandbox.io/s/mui-formik-fr93hm?file=/src/MyComponent.js but this approach uses the <Formik /> as opposed to useFormik which would change up my entire page but I'm in process to try anyway

I think the problem is that value of TextField is not value of formik. so the TextField is not controlled and by chaning value of formik it won't change.

assigning value of formik to it will do what you want

value={formik.values.firstName}

like this:

 <TextField
       onChange={formik.handleChange}
       id="product_name"
       value={formik.values.firstName}
       onBlur={formik.handleBlur}
       error={formik.touched.product_name && Boolean(formik.errors.product_name)}
       helperText={formik.touched.product_name && formik.errors.product_name}
     />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM