gerhat / material-ui-formik-components

Formik ready material ui components
MIT License
85 stars 13 forks source link

Refresh values not working for Select #27

Closed multivoltage closed 4 years ago

multivoltage commented 4 years ago

Please consider this scenario https://codesandbox.io/s/material-ui-formik-components-ychoc?file=/src/index.js

The scenario simulate: render a form with 0 fields. Fetch some api for an user Fill form with this data.

I used enableReinitialize to init the form when initialValues change. For some reason when I fill my fields array with some values (values that did not existing before) the select cannot show selected value.

My workaround is to build all my field before render the form, eve is all are empty. Then it works.

gerhat commented 4 years ago

@multivoltage I guess you also get the following warning:

Material-UI: a component is changing the uncontrolled value state of SelectInput to be controlled. Elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled SelectInput element for the lifetime of the component. The nature of the state is determined during the first render, it's considered controlled if the value is not undefined.

Initializing the fields with values is a requirement imposed by Formik and React. In Formik docs it reads:

Even if your form is empty by default, you must initialize all fields with initial values otherwise React will throw an error saying that you have changed an input from uncontrolled to controlled.

https://jaredpalmer.com/formik/docs/api/formik#initialvalues-values