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
6
7export function setDbClientContext(client: DbClientContext): DbClientContext {
8 return setContext(dbClientContext, client)
9}
10
11export function useDbClient(): DbClient {
12 const client = useOptionalDbClient()
13 if (!client) {
14 throw new Error(`useDbClient must be used within a DbProvider.`)
15 }
16 return client
17}
18
19export function useOptionalDbClient(): DbClient | undefined {
20 try {
21 return getContext<DbClientContext | undefined>(dbClientContext)?.()
22 } catch {
23 // Legacy helpers may be called from a rune root rather than a component.
24 return undefined
25 }
26}