Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate a React Formik form?

Tags:

reactjs

formik

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?

like image 871
Jason Avatar asked Dec 14 '22 11:12

Jason


1 Answers

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.

like image 198
Dan Avatar answered Dec 30 '22 11:12

Dan