#Preventing a specific query from triggering `onError`

4 messages · Page 1 of 1 (latest)

valid palm
#

I have the following client setup

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 2,
      staleTime: Infinity,
    },
  },
  queryCache: new QueryCache({
    onError: (error) => toast.error(error.message),
  }),
});

And in my RootRoute, I fetch user data on beforeLoad function and immediately showing the pendingCompoent. When the query fails, it triggers the toast.error and then redirects.

export const Route = createRootRoute({
  pendingMs: 0,
  pendingMinMs: 1000,
  // wrapInSuspense: https://github.com/TanStack/router/pull/1611
  wrapInSuspense: true,
  beforeLoad: async () => {
    try {
      await queryClient.fetchQuery({
        retry: 1,
        queryFn: getCurrentUserQuery,
        queryKey: ['current_user'],
      });
    } catch {
      redirect({ to: '/sign_in' });
    }
  },
  pendingComponent: () => <h1>Loading...</h1>,
  component: () => (
    <>
      <Navigator />
      <Outlet />
      <TanStackRouterDevtools />
    </>
  ),
});

Is there a way to prevent this specific query used in beforeLoad to trigger the toast message?

slow pecan
#

this is a question better suited in #1020327831592509480
however, since I know the answer I will add it here 🙂

#

in your case, I would use the query meta functionality to tag a query as "do not show the error" as follows:

  1. register a type for the queryMeta property

declare module '@tanstack/react-query' {
  interface Register {
    queryMeta: {swallowError?: boolean}
  }
}
  1. only show the toast if swallowError is falsy:
export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 2,
      staleTime: Infinity,
    },
  },
  queryCache: new QueryCache({
    onError: (error, query) => {if (!query.meta?.swallowError) { toast.error(error.message) },
  }),
});
  1. in your loader, set swallowError to true:
 await queryClient.fetchQuery({
        retry: 1,
        queryFn: getCurrentUserQuery,
        queryKey: ['current_user'],
        meta: { swallowError: true },
      });