DEV Community

Discussion on: React Form using Formik, Material-UI and Yup.

Collapse
 
finallynero profile image
Nero Adaware
How can I get the values from the form to submit them?

pass a submit function to formik onSubmit prop.


// submit function
submitValues = ({ name, email, confirmPassword, password }) => {
    console.log({ name, email, confirmPassword, password });
  };
    <Formik
              render={props => <Form {...props} />}
              initialValues={values}
              validationSchema={validationSchema}
              onSubmit={this.submitValues}
            />

Formik then provides you with a handleSubmit prop which you use to handle submit in your form.

 <form onSubmit={handleSubmit}>
......

</form>

handleSubmit basically passes all the values in your form to the submit function you passed to onSubmit

how can I set the value to the state if it has been fetched from the database

I didn't use state for my initial values in the article but it's possible use state.

create state values

this.state={
username:''
}

then in your componentdidmount or where ever you make your database calls you can setstate of that value.

componentdidmount(){
//database call
this.setState({username: databaseUsername})
}

then pass it to the Formik's initialValues prop


render(){
const {username} = this.state

const values = {username: username}

return(
<Formik
              render={props => <Form {...props} />}
              initialValues={values}
              validationSchema={validationSchema}
              onSubmit={this.submitValues}
            />

)
}

Link to demo