0
votes

I am trying to have the form I created with Formik and Yup send me an email "onSubmit" but I am not sure what I need to add to my "onSubmit" function to get this to work. Or do I need a handleSubmit and if so I would I write that out to get it to send me an email?

function Contact(){
return (
   <Formik
    initialValues={{
        name: '',
        email: '',
        message: '',
    }}
    validationSchema={Yup.object({
        name: Yup.string()
            .required('Required'),
        email: Yup.string()
            .email('Invalid Email Address')
            .required('Required'),
        message: Yup.string()
            .min(7, 'More details are always helpful.')
            .required('Required')
    })}
    onSubmit={(values, { setSubmitting, resetForm }) => {
        setTimeout(() => {
            resetForm();
            setSubmitting(false);
        }, 3000)
    }}
   >
       {props => (
           <Form>
               <h4>Shoot me a message here.</h4>

               <div className="field half first">
                    <CustomTextInput label="Name" name="name" type="text" placeholder="Enter Name" />
               </div>

               <div className="field half">
                    <CustomTextInput label="Email" name="email" type="email" placeholder="Enter Your Email" />
               </div>

               <div className="field">
                    <CustomTextarea label="message" name="message" rows="4" placeholder="Your Message Here" />
               </div>

               <button type="submit" className="special">{props.isSubmitting ? 'Sending...' : 'Send Message'}</button>
           </Form>
       )}
   </Formik>
1

1 Answers

0
votes

I think here is the approach you should take:

function Contact() {
  const sendDataToEmailApi = (values) => {
    // call your email api with the values
    return true; // to show the send process was successful
  };

  const handleSubmit = (values, { setSubmitting, resetForm }) => {
    const emailWasSent = sendDataToEmailApi(values);
    if (emailWasSent) {
      resetForm();
      setSubmitting(false);
    }
  };

  const validationSchema = Yup.object({
    name: Yup.string().required("Required"),
    email: Yup.string().email("Invalid Email Address").required("Required"),
    message: Yup.string()
      .min(7, "More details are always helpful.")
      .required("Required"),
  });

  return (
    <Formik
      initialValues={{
        name: "",
        email: "",
        message: "",
      }}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      {/* ... */}
    </Formik>
  );
}