13

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.

Ruby
  • 2,207
  • 12
  • 42
  • 71

4 Answers4

25

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

KletskovG
  • 520
  • 4
  • 10
8

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.

Ruby
  • 2,207
  • 12
  • 42
  • 71
2

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.

Ryan Brockhoff
  • 617
  • 1
  • 7
  • 8
  • I agree. If the form is not dynamic, there's no need for this at all. – Ruby Dec 20 '21 at 11:39
  • After the form re-rendered, I was getting old input values that didn't match Formik's current state. Your #2 bullet above saved me. For those who have a similar issue, put a random key on your input to ensure React doesn't just re-use the old value. This is especially valuable on dynamic form fields that are constantly being refreshed due to other inputs. – efru Feb 09 '22 at 17:16
0

i've checked with enableReinitialize={true}. But its not working as much as expected. so wrote a useEffect like

 useEffect(() => {
        formik.setFieldValue('query_string', active?.query);
    }, [active])

it's worked !

Shahnad S
  • 983
  • 10
  • 17