@daveyplate/better-auth-tanstack
Version:
Tanstack hooks for better-auth
38 lines (31 loc) • 1.18 kB
text/typescript
import type { AnyUseQueryOptions, QueryClient } from "@tanstack/react-query"
import type { AnyAuthClient } from "../types/any-auth-client"
import type { AuthClient } from "../types/auth-client"
import type { AuthQueryOptions } from "./auth-query-provider"
export async function prefetchSession<TAuthClient extends AnyAuthClient>(
authClient: TAuthClient,
queryClient: QueryClient,
queryOptions?: AuthQueryOptions,
options?: Partial<AnyUseQueryOptions>
) {
const { error, data } = await (authClient as AuthClient).getSession()
const mergedOptions = {
...queryOptions?.queryOptions,
...queryOptions?.sessionQueryOptions,
...options
}
await queryClient.prefetchQuery({
...mergedOptions,
queryKey: queryOptions?.sessionKey,
queryFn: () => data as SessionData
})
type SessionData = TAuthClient["$Infer"]["Session"]
type User = TAuthClient["$Infer"]["Session"]["user"]
type Session = TAuthClient["$Infer"]["Session"]["session"]
return {
error,
data: data,
session: data?.session as Session | undefined,
user: data?.user as User | undefined
}
}