最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

React Query Stuck in Loading State on 406 Not Acceptable Response with Axios - Stack Overflow

programmeradmin1浏览0评论

I'm using React Query (@tanstack/react-query) to fetch RDF data from an API with Axios, but when the API returns a 406 Not Acceptable response, the query remains in a loading state indefinitely instead of transitioning to an error state.

Code Implementation:

Here's my setup:

Custom Hook (useRDF.ts):

import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import parseRdfToJSON, { Prefix, Triple } from "../services/rdfToJson";

const fetchRDFData = async (endpoint: string) => {
    const response = await axios.get(`/api/${endpoint}`, {
        headers: {
            Authorization: `Basic ${import.meta.env.VITE_AUTH_TOKEN}`,
            Accept: "text/turtle",
        },
    });

    return parseRdfToJSON(response.data);
};

function useRDF(endpoint: string = "") {
    const prefixesQuery = useQuery<Prefix[]>({
        queryKey: ["rdf", endpoint, "prefixes"],
        queryFn: async () => {
            const data = await fetchRDFData(endpoint);
            return data.prefixes;
        },
    });

    const triplesQuery = useQuery<Triple[]>({
        queryKey: ["rdf", endpoint, "triples"],
        queryFn: async () => {
            const data = await fetchRDFData(endpoint);
            return data.triples;
        },
    });

    const children = triplesQuery.data
        ? triplesQuery.data
              .filter(triple => triple.predicate.name === "contains")
              .map(triple => triple.object.value)
        : [];

    return {
        prefixes: prefixesQuery.data || [],
        triples: triplesQuery.data || [],
        children,
        prefixesLoading: prefixesQuery.isLoading,
        triplesLoading: triplesQuery.isLoading,
        prefixesError: prefixesQuery.error,
        triplesError: triplesQuery.error,
    };
}

export default useRDF;

Issue:

  • When the API returns a 406 Not Acceptable response, I see the error in the browser console:
    GET http://localhost:5173/api/repo/rest/UBOBU/MICROFILM/UBO8306198/277667/UBOBU_UBO8306198_277667B 406 (Not Acceptable)
    
  • However, React Query remains stuck in a loading state instead of transitioning to an error state.
  • This issue only happens with 406. Other errors (like 500 or 404) correctly transition useQuery into an error state.

What I Have Tried:

  1. Manually Checking Response Status in fetchRDFData:

    const fetchRDFData = async (endpoint: string) => {
        const response = await axios.get(`/api/${endpoint}`, {
            headers: { Accept: "text/turtle" },
        });
    
        if (response.status !== 200) {
            throw new Error(`Failed to fetch RDF data: ${response.status} ${response.statusText}`);
        }
    
        return parseRdfToJSON(response.data);
    };
    
    • Still stuck in loading when a 406 occurs.
  2. Forcing Axios to Reject Non-2xx Responses with validateStatus:

    const fetchRDFData = async (endpoint: string) => {
        const response = await axios.get(`/api/${endpoint}`, {
            headers: { Accept: "text/turtle" },
            validateStatus: (status) => status >= 200 && status < 300, // Reject non-2xx
        });
    
        return parseRdfToJSON(response.data);
    };
    
    • Same issue, React Query does not detect the error properly.
  3. Switching to ky (Alternative to Axios)

    • I tried replacing Axios with ky, but the issue persisted.

Expected Behavior:

  • If the API returns a 406, React Query should set isError: true and stop loading instead of remaining in a loading state.

Question:

  • Why is React Query not recognizing the 406 error and getting stuck in loading?
  • How can I properly handle this error so React Query transitions into an error state?
发布评论

评论列表(0)

  1. 暂无评论