Files
clean-architecture-frontend…/src/presentation/adapters/query/server-state-scope-provider.tsx
T

53 lines
1.2 KiB
TypeScript

import {
createContext,
type ReactNode,
useContext,
useSyncExternalStore,
} from "react";
import type {
CacheScopeSnapshot,
ServerStateScopeRuntime,
} from "../../../contracts/server-state-scope.ts";
const ServerStateScopeContext =
createContext<ServerStateScopeRuntime | null>(null);
export function ServerStateScopeProvider({
runtime,
children,
transitionFallback = null,
}: Readonly<{
runtime: ServerStateScopeRuntime;
children: ReactNode;
transitionFallback?: ReactNode;
}>) {
const phase = useSyncExternalStore(
runtime.subscribe,
runtime.getPhase,
runtime.getPhase,
);
const content =
phase === "READY"
? children
: phase === "DISPOSED"
? null
: transitionFallback;
return (
<ServerStateScopeContext.Provider value={runtime}>
{content}
</ServerStateScopeContext.Provider>
);
}
export function useServerStateScope(): CacheScopeSnapshot {
const runtime = useContext(ServerStateScopeContext);
if (!runtime) throw new Error("ServerStateScopeProvider is required");
return useSyncExternalStore(
runtime.subscribe,
runtime.getSnapshot,
runtime.getSnapshot,
);
}