The useMutation
hook in React-Query is used for handling mutations, such as form submissions, API calls that modify data on the server, etc. Here's how you can use useMutation
for handling form submissions in a React component:
First, make sure you have React-Query installed in your project:
bashnpm install react-query
Then, you can use useMutation
in your component:
javascriptimport React, { useState } from 'react';
import { useMutation } from 'react-query';
const submitFormData = async (formData) => {
// Replace this with your API call to submit the form data
const response = await fetch('YOUR_API_ENDPOINT', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error('Failed to submit form data');
}
return response.json();
};
const MyFormComponent = () => {
const [formData, setFormData] = useState({
// Initialize your form data state
name: '',
email: '',
// Add more fields as needed
});
const mutation = useMutation(submitFormData);
const handleSubmit = async (event) => {
event.preventDefault();
try {
// Call the mutation function with the form data
await mutation.mutateAsync(formData);
// Handle successful form submission
console.log('Form submitted successfully');
} catch (error) {
// Handle form submission error
console.error('Form submission error:', error);
}
};
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
{/* Add more input fields here */}
<button type="submit">Submit</button>
</form>
);
};
export default MyFormComponent;
In this example:
submitFormData
function that represents the API call to submit the form data. You need to replace 'YOUR_API_ENDPOINT'
with your actual API endpoint.useMutation
hook to create a mutation instance. The submitFormData
function is passed as the mutation function.handleSubmit
function. We call mutation.mutateAsync(formData)
to execute the mutation (i.e., submit the form data).handleSubmit
function logs a success message to the console. If there's an error, it logs an error message instead.handleChange
function updates the form data as the user types in the input fields.React-Query will handle the loading state, error state, and cache management for you, providing a clean and efficient way to handle form submissions in your React application.