Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting a Formik Form on Unmount

Tags:

reactjs

formik

Is it possible to submit a Formik Form without having a submit button? For example submitting the Form when the component unmounts so the user doesn't need to click a button to save. Think of something like that:

import React from "react";
import { Formik, Form, Field } from "formik";

const Example = () => {
  useEffect(() => {
    return () => {
      //trigger Submit or send Request with Form Values from here
    };
  }, []);

  return (
    <Formik
      initialValues={{
        firstName: "",
        lastName: "",
      }}
      onSubmit={(values, { setSubmitting }) => {
        //send Request
      }}
    >
      {() => (
        <Form>
          <Field name="firstName" />
          <Field name="lastName" />
        </Form>
      )}
    </Formik>
  );
};

export default Example;
like image 210
lucaplaysthenoob Avatar asked Sep 19 '25 00:09

lucaplaysthenoob


1 Answers

You can create a functional component that auto-submits. By having it render inside the component, you have reference to the context of the form. You can use:

import { useFormikContext } from 'formik';
 
 function AutoSubmitToken() {
   // Grab values and submitForm from context
   const { values, submitForm } = useFormikContext();

   React.useEffect(() => {
     return submitForm;
   }, [submitForm]);
   return null;
 };

You can use it under the component as such

<Form>
   <Field name="token" type="tel" />
   <AutoSubmitToken />
</Form>

You can read all about it here

like image 168
Matt Avatar answered Sep 21 '25 14:09

Matt