TanStackT
TanStack3mo ago
4 replies
spotty-amber

Is it possible to access browser QueryClient without passing it as a function parameter?

I couldn't seem to find a quick answer, but I have a
beforeLoad
that I'd like to call to verify permissions and since I'm use Tanstack Query I want to use ensureQueryData so I can utilize browser cache if it exists. I would like to extract the logic in to a function and I was curious if I could access my client without needing to pass it as a function parameter?

const hasPermission = async (queryClient: QueryClient, permission: PermissionEnum) => {
    // implementation...

    await queryClient.ensureQueryData(...)
}

export const Route = createFileRoute("/workspace")({
    beforeLoad: async ({ context, params }) => {

        // i would like to avoid this
        await hasPermission(context.queryClient, "contact-list.read")
    },
    component: RouteComponent,
})


I know I could put this function in my context but I guess I'm just asking conceptually how to access the browser QueryClient outside react land? In nextjs, tanstack query has a getQueryClient you could export https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#initial-setup to ensure you were grabbing the same query client on the browser but a new instance on each server request. Is it okay to do something similar like the below so i can just import getQueryClient in my client side functions?

let browserQueryClient: QueryClient | undefined = undefined

export function getQueryClient() {
    if (typeof window === "undefined") {
        return new QueryClient()
    } else {
        if (!browserQueryClient) browserQueryClient = new QueryClient()
        return browserQueryClient
    }
}

export function getRouter() {
    const queryClient = getQueryClient()

    const router = createRouter({
        routeTree,
        context: { queryClient },
        defaultPreload: "intent",
        scrollRestoration: true,
    })

    setupRouterSsrQueryIntegration({
        router,
        queryClient,
    })

    return router
}


Thanks a lot!
Welcome to the Advanced Server Rendering guide, where you will learn all about using React Query with streaming, Server Components and the Next.js app router. You might want to read the before this on...
Advanced Server Rendering | TanStack Query React Docs
Was this page helpful?