[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
loading
indicator - GraphQL response gets returned, apollo updates underlying bound components
- Form gets filled with response data,
loading
indicator 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 GitHub Comments
If you use the
<Formik>
component you should be able to passenableReinitialize
, which will reinitialize when it detects yourinitialValues
have 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 ->MyForm
re-renders -> Formik detects change ininitialValues
-> Formik reinitializes the form.That said, you could also very easily block rendering of
<Formik ... />
and just returnnull
or a<Loader />
as long isthis.props.data.user === undefined
. Depends what behavior you want.Looking at your gist that’s normal, since your
values
will beundefined
until apollo gets a response back from your query. 2 options:emptyFormState
example) sinceinput
components will throw that uncontrolled-to-controlled warning when you initialize them withundefined
.this.props.data.user !== undefined
orthis.props.loading === false
.