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:

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:

Photo from Unsplash
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.
you can extract the
setSubmitting
property and call it inside theonSubmit
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);
}
});
}