Formik - Update initial values after API call

Viewed 10386

I'm getting my inputs dynamically from an API call based on a change in select input, but when I try to add to the initial values of Formik, it always gives me an error ...

Warning: A component is changing an uncontrolled input of type text to be controlled.

And it doesn't help if I set enableReinitialize={true} to Formik.

However, if I generated the inputs from a local JSON or object, the error goes away.

What am I doing wrong here ...

https://codesandbox.io/s/test-dynamic-inputs-with-formik-xr9qg

The form submits fine though.

3 Answers

Better use enableReinitialize={true}. This is official Formik API. You can check this issue

If anyone is facing the same issue, I just found the solution ...

You have to set value={field.value || ''} in the input inside the TextInput component or whatever type you're using in order to fix this issue.

I had a complex, dynamic form and also came across this issue. There are a few things that I'd recommend for anyone debugging this issue in the future:

  1. Set value for your Field component--like Ruby does above.
  2. Ensure that your Formik component has a uniquely identifying key.
  3. Track and debug your initialValues and ensure that all fields are accounted for. You shouldn't have to set the field value like Ruby does--so long as your initialValues object accounts for all of the fields. However, my form dynamically changed Field components--and Ruby's solution is the only one that worked.

If your form is not dynamic--I think it might be best to check your initialValues object first before implementing Ruby's solution. Formik should be taking care of those values for you--which is why it's such an awesome tool.

Related