Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react formik - fill form inputs with data after http request

I created form with formik. I want to edit record with the form. I want to fetch data from database and fill the form with them. However with no success.

Here is my code.

class UserForm extends Component {

  componentWillMount(){
    this.setState({firstName:''})
    var repository = new Repository();
    repository.getUser(function(user){
       this.setState({
        firstName: user.firstName,
       });
    }.bind(this),this.props.currentId)        
  }

  render() {
    return (
      <Formik
      initialValues={{
        firstName: this.state.firstName,
      }}
        validationSchema = {Yup.object().shape({
          firstName: Yup.string().required('First name is required'),

        })}
      onSubmit={item => { this.props.addRecordToTable(item)}}
      render={({ setFieldValue, values, errors, touched, isSubmitting }) =>
        <Form>
        <div>
          { touched.firstName && errors.firstName && <p>{errors.firstName}</p> }
          <Field type="input" name="firstName" placeholder="First name"/>
        </div>
        <input type="submit"></input>
      </Form>}
    />
    );
  }
}

export default UserForm;

Input firstName will never be filled with loaded data. How can i solve this?

like image 608
kostik Avatar asked Apr 22 '18 14:04

kostik


1 Answers

Set enableReinitialize to true in <Formik ... />

like image 139
shackra Avatar answered Sep 18 '22 17:09

shackra