Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass state values to initial values in formik in react js

Tags:

I'm using formik library in my react application. Initially, I declared state values in the constructor, In componentDidMount I'm calling an API with that app response am updating state values, Can anyone help me in passing state values to fomik initial values

In my situation formik taking initial state values which are declared in the constructor.thanks in advance

class Dropdown extends Component {          constructor(props) {             super(props);             this.state = {               //some data             };           }           componentDidMount() {            //api call            this.setState( {               //update state values with api response data             });            }        render() {             return (             <Formik               initialValues={this.state}               validate={validate(validationSchema)}               onSubmit={onSubmit}               render={                 ({                   values,                   errors,                   touched,                   status,                   dirty,                   handleChange,                   handleBlur,                   handleSubmit,                   isSubmitting,                   isValid,                   handleReset,                   setTouched                 }) => (                   //form uses initialValues               )} />               )             }     } 
like image 239
Abhiram Avatar asked Dec 25 '18 07:12

Abhiram


People also ask

How do I get Formik values before submitting?

it is very simple just do console. log(formik. values) and you will get all the values without submitting it.

What is dirty Formik?

Returns true if values are not deeply equal from initial values, false otherwise. dirty is a readonly computed property and should not be mutated directly.


2 Answers

Adding enableReinitialize to formik solved my issue

     <Formik           enableReinitialize           ..           render={             ({               ..             }) => (               //form uses initialValues           )} /> 
like image 60
Abhiram Avatar answered Oct 05 '22 23:10

Abhiram


Answer credit to Abhiram, but in case you have updated to hooks:

useFormik({   initialValues: initialData,   enableReinitialize: true,   onSubmit: values => {     // Do something   } }); 
like image 25
grumpyTofu Avatar answered Oct 05 '22 23:10

grumpyTofu