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 =>'/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) => {
    mutate({ text: postText });

  return (
    <form onSubmit={handleSubmit}>
      <textarea value={postText} onChange={(e) => setPostText(}></textarea>
      <button type="submit" disabled={isLoading}>Submit Post</button>
      {isError && <div>Failed to submit post. Please try again.</div>}
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.