Submit formik form using React-Query mutations

In this article you will learn how to create forms using Formik library, and how to submit the forms using React-Query mutation hook.

We will cover the following items:

  • Build a simple form using Formik and useFormik hook.
  • Use UI components from Material/Core library.
  • Handle form validation using Yup.
  • Handle form submittion using React-Query useMutation hook.

Let’s dig in, and start by building the form component.

It will be a simple Signup form that consisting of two fields: Full name and Email.

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      fullName: "",
      email: ""
    },
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    }
  });

  return (
    <div>
      <form onSubmit={formik.handleSubmit}>
        <TextField
          fullWidth
          id="fullName"
          name="fullName"
          label="Full Name"
          value={formik.values.fullName}
          onChange={formik.handleChange}
          error={formik.touched.fullName && Boolean(formik.errors.fullName)}
          helperText={formik.touched.fullName && formik.errors.fullName}
        />

        <TextField
          fullWidth
          id="email"
          name="email"
          label="Email"
          value={formik.values.email}
          onChange={formik.handleChange}
          error={formik.touched.email && Boolean(formik.errors.email)}
          helperText={formik.touched.email && formik.errors.email}
        />

        <Button color="primary" variant="contained" fullWidth type="submit">
          Submit
        </Button>
      </form>
    </div>
  );
};

Add form validation using Yup

Let’s create the validationSchema object, which will be of type Yup.object, and add the validation requirements to each field, as the following:

const validationSchema = yup.object({
  fullName: yup
    .string("Enter your full name")
    .required("Full Name is required"),
  email: yup
    .string("Enter your email")
    .email("Enter a valid email")
    .required("Email is required")
});

Now, let’s assign/pass the validation schema object for formik instance, as the following:

  const formik = useFormik({
    initialValues: {
      fullName: "",
      email: ""
    },
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    },
++  validationSchema: validationSchema,
  });

By this staging, you should have the form is ready and working as expected, as shown below:

Submit formik form using React-Query mutations
Submit formik form using React-Query mutations

Adding the implementation for the Reacy-Query useMutation hook

We are going to use a mocked api server to submit the form against it, also we will use Axios in order to send HTTP request against the mocked api server.

First, let’s create the useMutation wrapper, with the implementation to submit the request against the mocked server.

import { useMutation } from "@tanstack/react-query";

const useSignupMutation = () => {
  return useMutation((formPayload) => {
    return axios.post(
      "https://jsonplaceholder.typicode.com/users",
      formPayload
    );
  });
};

Then, we need to call the useSignupMutation hook inside the Signup form, and destruct the mutate function out of it, as the following:

const SignupForm = () => {
  const { mutate } = useSignupMutation();
....

After that, we need to update the onSubmit function to use the mutate function as the following:

  onSubmit: (values) => {
    mutate(values, {
      onSuccess: () => {
        alert("Form submitted successfully");
      },
      onError: (response) => {
        alert("An error occured while submiting the form");
        console.log(response);
      }
    });
  }

In the above sample, we called the mutate on submit, and we passed the form values as the first argument. Then, we’ve added a success/failure callbacks listeners, in both cases we will receive a feedback if the form submit was successfull or not.


Now, putting all the implementation together, we would get the following:

import React from "react";
import ReactDOM from "react-dom/client";
import {
  QueryClient,
  QueryClientProvider,
  useMutation
} from "@tanstack/react-query";
import axios from "axios";
import { useFormik } from "formik";
import * as yup from "yup";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";

const queryClient = new QueryClient();

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <SignupForm />
    </QueryClientProvider>
  );
}

const useSignupMutation = () => {
  return useMutation((formPayload) => {
    return axios.post(
      "https://jsonplaceholder.typicode.com/users",
      formPayload
    );
  });
};

const validationSchema = yup.object({
  fullName: yup
    .string("Enter your full name")
    .required("Full Name is required"),
  email: yup
    .string("Enter your email")
    .email("Enter a valid email")
    .required("Email is required")
});

const SignupForm = () => {
  const { mutate } = useSignupMutation();

  const formik = useFormik({
    initialValues: {
      fullName: "",
      email: ""
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      mutate(values, {
        onSuccess: () => {
          alert("Form submitted successfully");
        },
        onError: (response) => {
          alert("An error occured while submiting the form");
          console.log(response);
        }
      });
    }
  });

  return (
    <div>
      <form onSubmit={formik.handleSubmit}>
        <TextField
          fullWidth
          id="fullName"
          name="fullName"
          label="Full Name"
          value={formik.values.fullName}
          onChange={formik.handleChange}
          error={formik.touched.fullName && Boolean(formik.errors.fullName)}
          helperText={formik.touched.fullName && formik.errors.fullName}
        />

        <TextField
          fullWidth
          id="email"
          name="email"
          label="Email"
          value={formik.values.email}
          onChange={formik.handleChange}
          error={formik.touched.email && Boolean(formik.errors.email)}
          helperText={formik.touched.email && formik.errors.email}
        />

        <Button color="primary" variant="contained" fullWidth type="submit">
          Submit
        </Button>
      </form>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.createRoot(rootElement).render(<App />);

Trying to submit the form after we’ve the whole implementation is ready, we would get the following in case of successful submission:

Submit formik form using React-Query mutations
Submit formik form using React-Query mutations

Full source code

Photo from Unsplash

Related Posts

How to Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

This Post Has 2 Comments

  1. How to handle the submitting state of the form? formik does not know about the promise inside handleSubmit, which will leave the isSubmitting value in formik as true even if the API is settled.

  2. you can extract the setSubmitting property and call it inside the onSubmit handler as in the example below:
    onSubmit: (values, {setSubmitting}) => {
    setSubmitting(true);
    mutate(values, {
    onSuccess: () => {
    alert("Form submitted successfully");
    setSubmitting(false);
    },
    onError: (response) => {
    alert("An error occured while submiting the form");
    console.log(response);
    setSubmitting(false);
    }
    });
    }

Leave a Reply

%d bloggers like this: