TanStackT
TanStack3y ago
25 replies
foolish-indigo

Error Handling with Fetch works but isError always returns False

So I am using NextJS with page router, and in my code, I have an API that can return either a status 200 with the data or several other status codes (404, 403, and 500) depending on access permissions.

Following the docs, I wrote my react query function as follows:
export async function getPlanFn(planId: string) {
  const res = await fetch(`/api/controllers/plan?planId=${planId}`);

  if (!res.ok) {
    const error = (await res.json()) as Error;
    throw new Error(error.message);
    // return Promise.reject(error.message);
  }

  return res.json()
}

export function useGetPlan(planId: string) {

  return useQuery({
    queryKey: ["plan", "123"],
    queryFn: () => getPlanFn(planId),
    enabled: planId !== undefined || planId !== null,
    refetchInterval: 1000 * 10, // get new data every 10 secs
  });
}


and my I access this function on my [plan].tsx page as such:
const {
    isLoading,
    isError,
    error,
    data: trip,
  } = useGetPlan(planId as string);


I'm finding that the error shows up from getPlanFn, but isError is always FALSE (please see photo for reference). Why might that be happening?

I would appreciate the help on this because I've been struggling for the past 2 hours, trying to figure out what is wrong.
Screenshot_2023-11-23_at_15.39.41.png
Was this page helpful?