kostik
kostik

Reputation: 693

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?

Upvotes: 7

Views: 5678

Answers (1)

shackra
shackra

Reputation: 376

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

Upvotes: 10

Related Questions