Ruby
Ruby

Reputation: 2909

Formik - Update initial values after API call

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.

Upvotes: 15

Views: 20462

Answers (4)

Shahnad S
Shahnad S

Reputation: 1167

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 !

Upvotes: 1

KletskovG
KletskovG

Reputation: 550

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

Upvotes: 27

Ryan Brockhoff
Ryan Brockhoff

Reputation: 706

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.

Upvotes: 2

Ruby
Ruby

Reputation: 2909

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.

Upvotes: 9

Related Questions