13

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?

James Z
  • 12,209
  • 10
  • 24
  • 44
Manoj Sethi
  • 1,898
  • 8
  • 26
  • 56
  • 9
    I am sorry I am able to fix it. On button click, I need not pass submitForm as button type is 'submit'. It was a silly mistake of mine. Sorry to bother you who came here for help and I hope if somebody is facing such issue it helps them. – Manoj Sethi May 02 '20 at 10:34
  • 5
    thanks mate, I was having the same issue. Right, that was a silly mistake – Adam Kosmala Aug 14 '20 at 08:15

3 Answers3

10

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}
>
CristianR
  • 373
  • 4
  • 8
0

Be sure to NOT add both
onClick={formik.formik.handleSubmit}
and
<form onSubmit={formik.handleSubmit}>.

Should be one or the other.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
-1

I faced the same issue. Adding e.preventDefault() in my Form Submit Handler worked for me.

onSubmitHandler = (e) => {
e.preventDefault();
//Handle submission
}