Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Formik onSubmit Async called twice

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?

like image 752
Manoj Sethi Avatar asked May 02 '20 10:05

Manoj Sethi


1 Answers

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}
>
like image 57
CristianR Avatar answered Sep 21 '22 08:09

CristianR