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 remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: