Update Post with UseMutation Hook in React js 2025

Update Post with useMutation Hook in React JS 2025

Agar aap kisi post ko update karna chahte ho React Query ke useMutation hook se, to aapko ek API call likhna hoga jo PUT ya PATCH method ka use kare. Neeche complete example diya gaya hai:

1. Update Function (API Call)


import axios from "axios";

const updatePost = async ({ id, updatedData }) => {
  const response = await axios.put(
    `https://jsonplaceholder.typicode.com/posts/${id}`,
    updatedData
  );
  return response.data;
};
  

2. useMutation Hook


import { useMutation, useQueryClient } from "@tanstack/react-query";

const queryClient = useQueryClient();

const mutation = useMutation({
  mutationFn: updatePost,
  onSuccess: () => {
    alert("Post updated successfully!");
    queryClient.invalidateQueries(["posts"]); // Refresh post list
  },
  onError: () => {
    alert("Failed to update post");
  }
});
  

3. Form with Update Button


function UpdatePostForm() {
  const [title, setTitle] = useState("Updated title");
  const [body, setBody] = useState("Updated content");

  const handleUpdate = () => {
    mutation.mutate({
      id: 1,
      updatedData: {
        title: title,
        body: body,
      },
    });
  };

  return (
    
setTitle(e.target.value)} />