Open History to see the last commit
1import { getContext, setContext } from 'svelte'
2import type { DbClient } from '@tanstack/db'
3
4const dbClientContext = Symbol.for(`@tanstack/svelte-db.DbClient`)
5type DbClientContext = () => DbClient
6type ScopedDbContext = { client: DbClient; hydrating: boolean | undefined }
7
8export function setDbClientContext(
9 client: DbClientContext,
10 hydrating?: () => boolean,
11): DbClientContext {
12 setContext(dbClientContext, () => ({
13 client: client(),
14 hydrating: hydrating?.(),
15 }))
16 return client
17}
18
19export function useDbClient(): DbClient {
20 const client = useOptionalDbClient()
21 if (!client) {
22 throw new Error(`useDbClient must be used within a DbProvider.`)
23 }
24 return client
25}
26
27export function useOptionalDbClient(): DbClient | undefined {
28 return useDbContext()?.client
29}
30
31// Client ownership and initial host intent belong to the same provider scope.
32// Reading both together avoids another context key or a second context lookup.
33export function useDbContext(): ScopedDbContext | undefined {
34 try {
35 return getContext<(() => ScopedDbContext) | undefined>(dbClientContext)?.()
36 } catch {
37 // Legacy helpers may be called from a rune root rather than a component.
38 return undefined
39 }
40}