TanStackT
TanStack2mo ago
2 replies
still-lime

global queryClient.invalidateQueries() on error?

I found this code in a starter template:

export const queryClient = new QueryClient({
    queryCache: new QueryCache({
        onError: (error) => {
            toast.error(`Error: ${error.message}`, {
                action: {
                    label: "retry",
                    onClick: () => {
                        queryClient.invalidateQueries();
                    },
                },
            });
        },
    }),
});


It looks off to me, so I changed it to:

export const queryClient = new QueryClient({
    queryCache: new QueryCache({
        onError: (error, query) => {
            toast.error(`Error: ${error.message}`, {
                action: {
                    label: "retry",
                    onClick: query.invalidate,
                },
            });
        },
    }),
});


Is this the correct way to handle per-query errors?

My logic:
- The original code invalidates all queries on error, which seems too broad.
- My version uses the query argument to only invalidate the failed query via query.invalidate.

Is this the right approach for handling errors and retries in TanStack Query? Any best practices here? Thanks.
Was this page helpful?