How do I populate a React Formik form? Like for e.g. to edit a record, populate the existing data into the fields first.
I tried something like:
componentDidMount(){
...
// get data from api call,
this.username = ...
this.email = ...
}
render(){
return(
<Formik initialValues={{ username: this.username, email: this.email }}
)
}
but the form always turns out empty. I guess that's also because render is called before componentDidMount. So how do I populate a Formik form?
For this use case, you should set enableReinitialize
on the form.
https://jaredpalmer.com/formik/docs/api/formik#enablereinitialize-boolean
enableReinitialize?: boolean Default is false.
Control whether Formik should reset the form if initialValues changes (using deep equality).
This will cause Formik to change any time a value in initialValues
changes - You should take care to ensure the stability of the values within initialValues
when enabling this.
Formik does use deep value equality to determine if there's a change, which means it will compare the value of fields within the object rather than the object reference itself to determine if there was a change.
You should store fields from a remote source in component state using this.setState()
- setting the fields on the controller instance will prevent React from re-rendering in response to the field changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With