38 lines
972 B
TypeScript
38 lines
972 B
TypeScript
import { useAuthToken } from "@convex-dev/auth/react"
|
|
import { userIdFromToken } from "@otunes/convex/client/auth-token"
|
|
import { createContext, useContext, useMemo, type ReactNode } from "react"
|
|
|
|
import { loadPersistentCache } from "@/lib/persistent-cache"
|
|
|
|
export const ANONYMOUS_CACHE_SCOPE = "anon"
|
|
|
|
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
|
|
|
|
void loadPersistentCache()
|
|
|
|
/** Namespaces persisted client data by server and signed-in user. */
|
|
export function PersistentCacheProvider({
|
|
serverUrl,
|
|
children,
|
|
}: {
|
|
serverUrl: string
|
|
children: ReactNode
|
|
}) {
|
|
const token = useAuthToken()
|
|
const userId = userIdFromToken(token)
|
|
const scope = useMemo(
|
|
() => (userId ? `${serverUrl}|${userId}` : ANONYMOUS_CACHE_SCOPE),
|
|
[serverUrl, userId]
|
|
)
|
|
|
|
return (
|
|
<CacheScopeContext.Provider value={scope}>
|
|
{children}
|
|
</CacheScopeContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useCacheScope() {
|
|
return useContext(CacheScopeContext)
|
|
}
|