Updating Data with useMutation Custom Hook
Illustrate the process of creating a custom hook that uses the useMutation hook for submitting new posts to an API, including handling the mutation's success and error states.
import { useMutation } from 'react-query';
import axios from 'axios';
This imports the useMutation hook from react-query and axios for making HTTP requests.
const useSubmitPost = () => {
return useMutation(postData => axios.post('/api/posts', postData), {
onSuccess: () => {
// Handle successful submission here
console.log('Post submitted successfully');
},
onError: (error) => {
// Handle submission error here
console.error('Error submitting post:', error);
}
});
};
Defines a custom hook, useSubmitPost, utilizing useMutation to submit new posts. It manages both success and error states.
import { useState } from 'react';
const NewPostForm = () => {
const [postText, setPostText] = useState('');
const { mutate, isLoading, isError } = useSubmitPost();
const handleSubmit = (e) => {
e.preventDefault();
mutate({ text: postText });
setPostText('');
};
return (
<form onSubmit={handleSubmit}>
<textarea value={postText} onChange={(e) => setPostText(e.target.value)}></textarea>
<button type="submit" disabled={isLoading}>Submit Post</button>
{isError && <div>Failed to submit post. Please try again.</div>}
</form>
);
};
Demonstrates how to use the custom hook, useSubmitPost, in a form component to submit new posts. Manages loading state and error feedback to the user.