[Next] Should form automatically reset if passed-in props change?
See original GitHub issueThe scenario I’m trying to implement is the following:
- User clicks “edit”
- GraphQL query gets dispatched, form gets rendered with
loadingindicator - GraphQL response gets returned, apollo updates underlying bound components
- Form gets filled with response data,
loadingindicator gets removed
The problem I’m running into is that mapPropsToValues() only gets called in the constructor and not in componentWillReceiveProps(), and as a result Formik never updates the form with the received values and just renders the empty state. Is there any way around this right now, or is this not supported?
With a slightly hacky workaround I’m currently passing down the values as a different prop so they reach the form component itself, where I’m doing a this.props.resetForm() whenever the prop changes. Does the job for now, but wondering if we could just use componentWillReceiveProps() in Formik itself. I realize it can be a bit tricky but by checking if the previous values prop were falsy and/or the values state is not dirty this should be rather safe I think.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:12 (1 by maintainers)

Top Related StackOverflow Question
If you use the
<Formik>component you should be able to passenableReinitialize, which will reinitialize when it detects yourinitialValueshave changed. So what should work is something like this:Your user query data starts off
undefined-> apollo fires the request -> apollo receives the response -> user prop gets updated ->MyFormre-renders -> Formik detects change ininitialValues-> Formik reinitializes the form.That said, you could also very easily block rendering of
<Formik ... />and just returnnullor a<Loader />as long isthis.props.data.user === undefined. Depends what behavior you want.Looking at your gist that’s normal, since your
valueswill beundefineduntil apollo gets a response back from your query. 2 options:emptyFormStateexample) sinceinputcomponents will throw that uncontrolled-to-controlled warning when you initialize them withundefined.this.props.data.user !== undefinedorthis.props.loading === false.