TanStackT
TanStack3y ago
9 replies
dead-brown

Mutation stuck at loading

Hi there! I've searched and found this issue that seems related: react-query-questionsMy Mutation is stuck in loading state after successful request

Basically I'm calling a mutation from an effect but its status remains loading . However, if I add the onSettled callback, data is defined so I don't understand what's wrong.

Here is a simplified version of my code, thanks in advance for the help!

"use client";
import {useMutation} from "@tanstack/react-query";
import {useSearchParams} from "next/navigation";
import {useEffect,useRef} from "react";

function usePackageAPI() {
  function api({path,method,headers,body}: {
    path: string;
    method: "GET" | "POST" | "PUT" | "DELETE";
    headers?: HeadersInit;
    body?: any;
  }) {
    return fetch("..." + path, {method,headers,body: body ? JSON.stringify(body) : null,});
  }

  async function process({ packageLink }: { packageLink: string }) {
    const data = await api({
      path: "/process",
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: { package_link: packageLink },
    }).then((res) => res.json());
    return data;
  }

  return { process };
}

export default function Page() {
  const searchParams = useSearchParams();
  const packageLink = searchParams?.get("packageLink") || undefined;
  const enabled = !!packageLink;
  const api = usePackageAPI();
  const isInitializedRef = useRef(false);
  const processMutation = useMutation({
    mutationKey: ["package-api", "process", packageLink],
    mutationFn: api.process,
    onSettled: (data) => console.log(data)
  });

  useEffect(() => {
    if (!enabled || isInitializedRef.current) return;
    isInitializedRef.current = true;
    processMutation.mutate({ packageLink });
  }, [enabled, packageLink, processMutation]);

  return (
<>
{processMutation.isSuccess ? <div>{JSON.stringify(processMutation.data, null, 2)}</div> : <div>{processMutation.status}</div>}
</>
  );
}
Was this page helpful?