43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import { ConvexAuthProvider } from "@convex-dev/auth/react"
|
|
import { ConvexReactClient } from "convex/react"
|
|
import { useCallback, useMemo, useState, type ReactNode } from "react"
|
|
|
|
import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session"
|
|
import { useServerConfig } from "@/contexts/server-config"
|
|
import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage"
|
|
|
|
export function ConvexAppProvider({ children }: { children: ReactNode }) {
|
|
const { config } = useServerConfig()
|
|
const [authEpoch, setAuthEpoch] = useState(0)
|
|
|
|
const client = useMemo(() => {
|
|
if (!config) return null
|
|
return new ConvexReactClient(config.convexUrl)
|
|
}, [config?.convexUrl, authEpoch])
|
|
|
|
const invalidateSession = useCallback(async () => {
|
|
if (!config) {
|
|
return
|
|
}
|
|
await clearStoredAuthTokens(config.convexUrl)
|
|
setAuthEpoch((epoch) => epoch + 1)
|
|
}, [config])
|
|
|
|
if (!client || !config) {
|
|
return <>{children}</>
|
|
}
|
|
|
|
return (
|
|
<ConvexAuthSessionProvider invalidateSession={invalidateSession}>
|
|
<ConvexAuthProvider
|
|
key={authEpoch}
|
|
client={client}
|
|
storage={secureStorage}
|
|
storageNamespace={config.convexUrl}
|
|
>
|
|
{children}
|
|
</ConvexAuthProvider>
|
|
</ConvexAuthSessionProvider>
|
|
)
|
|
}
|