35

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
              )} />
              )
            }
    }
Abhiram
  • 1,540
  • 1
  • 11
  • 25

3 Answers3

71

Adding enableReinitialize to formik solved my issue

     <Formik
          enableReinitialize
          ..
          render={
            ({
              ..
            }) => ( 
             //form uses initialValues
          )} />
Abhiram
  • 1,540
  • 1
  • 11
  • 25
16

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

useFormik({
  initialValues: initialData,
  enableReinitialize: true,
  onSubmit: values => {
    // Do something
  }
});
grumpyTofu
  • 826
  • 7
  • 5
1

You can imperatively set each value at initialValues prop:

 <Formik
  initialValues={
    formValue1: this.state.value1,
    formValue2: this.state.value2,
    ...
  }
  validate={validate(validationSchema)}
  onSubmit={onSubmit}
  render={
    ({
      values,
      errors,
      touched,
      status,
      dirty,
      handleChange,
      handleBlur,
      handleSubmit,
      isSubmitting,
      isValid,
      handleReset,
      setTouched
    }) => ( 
         //form uses initialValues
    )
  } 
/>
David Casanellas
  • 815
  • 2
  • 11
  • 18