Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

DbProvider.tsx

32 lines743 Bytes

1'use client'
2​
3import { createContext, useContext } from 'react'
4import type { DbClient } from '@tanstack/db'
5import type { ReactNode } from 'react'
6​
7const DbContext = createContext<DbClient | undefined>(undefined)
8​
9export type DbProviderProps = {
10 client: DbClient
11 children?: ReactNode
13​
14export function DbProvider(props: DbProviderProps) {
15 return (
16 <DbContext.Provider value={props.client}>
17 {props.children}
18 </DbContext.Provider>
19 )
21​
22export function useDbClient(): DbClient {
23 const client = useContext(DbContext)
24 if (!client) {
25 throw new Error(`useDbClient must be used within a DbProvider.`)
26 }
27 return client
29​
30export function useOptionalDbClient(): DbClient | undefined {
31 return useContext(DbContext)