TanStackT
TanStack2y ago
7 replies
ethical-tan

Retrieving body json when errors occur with useQuery

When my server responds with an error, it sometimes passes in an error message that is useful to the user. I want to pass that through to my React code but can't seem to do it, because I need to throw new Error and I'm unable to call the await response.json() in this GET function or else the useQuery stops working, because it expects the promise as the return value. If I throw the error and then modify the error after the fact with the response body, my react code doesnt update. I'm in a pickle.

my fetch code:
// Dead simple GET request
export const GET = async (endpoint: string, params?: Record<string, any>) => {
  const url = params ? `${endpoint}?${buildQueryString(params)}` : endpoint;
  const response = await fetch(url, init);

  if (!response.ok || response.status === 204) {
    // I want to passs in the await response.json() here to show my users
    throw new HTTPError(response);
  }
  return response.json();
};


my query
const { isFetching, data, error } = useQuery<IGridData>(moduleQueryOptions());


my react code
if (error) {
   <div className="flex h-full w-full flex-col items-center justify-center px-4 text-lg text-red-500">
      {RemapErrorMessage[error?.code] ?? error.message}
    </div>

but I want error.message to be the server response in some cases. Any advice?
Was this page helpful?