diff --git a/src/shared/api/provider.tsx b/src/shared/api/provider.tsx new file mode 100644 index 00000000..00505be3 --- /dev/null +++ b/src/shared/api/provider.tsx @@ -0,0 +1,41 @@ +import { createContext, useContext } from "react"; +import type { ReactNode } from "react"; +import type { ApiClient } from "./client.js"; + +const ApiClientContext = createContext(null); + +export interface ApiClientProviderProps { + client: ApiClient; + children: ReactNode; +} + +/** + * Provides the ApiClient instance to the React tree. SSR-aware: + * on the server, construct per-request with the resolved locale; + * on the client, share a single instance across the tab. + */ +export function ApiClientProvider({ + client, + children, +}: ApiClientProviderProps): JSX.Element { + return ( + + {children} + + ); +} + +/** + * Returns the ApiClient from context. Throws if used outside + * . + */ +export function useApiClient(): ApiClient { + const client = useContext(ApiClientContext); + if (!client) { + throw new Error( + "useApiClient() must be used within an . " + + "Ensure the root layout wraps the tree with .", + ); + } + return client; +}