I am trying to use async with onSubmit with following code for Formik in React
import React from "react";
import { Formik, Form, Field } from "formik";
import { Row, Col, Button } from "react-bootstrap";
const AddUser = () => {
const initialValues = {
name: "",
};
return (
<>
<Row className="h-100">
<Col xs={12} sm={1}></Col>
<Col xs={12} sm={10} className="align-self-center">
<div className="block-header px-3 py-2">Add Dataset</div>
<div className="dashboard-block dashboard-dark">
<Formik
initialValues={initialValues}
onSubmit={async (values, { setSubmitting }) => {
alert("hi");
setSubmitting(false);
}}
>
{({ isValid, submitForm, isSubmitting, values }) => {
return (
<Form>
<Field
name="name"
label="Name"
placeholder="Dataset Name"
/>
<Button
type="submit"
disabled={!isValid || isSubmitting}
className="w-100 btn btn-success"
onClick={submitForm}
>
Add Dataset
</Button>
</Form>
);
}}
</Formik>
</div>
</Col>
<Col xs={12} sm={1}></Col>
</Row>
</>
);
};
export default AddUser;
When I try to submit. It does alert 'hi' twice. When I don't use onSubmit as async then it works fine.
What am I doing wrong or is there any other way to perform async functionalities as I need to perform RestAPI calls?
Delete type="submit"
, because there is already an action onClick={submitForm}
<Button
type="submit"
disabled={!isValid || isSubmitting}
className="w-100 btn btn-success"
onClick={submitForm}
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With