Add ApiClient React context provider with useApiClient hook

This commit is contained in:
2026-04-14 23:46:20 +03:00
parent 04c5432aef
commit 7992d2705a
+41
View File
@@ -0,0 +1,41 @@
import { createContext, useContext } from "react";
import type { ReactNode } from "react";
import type { ApiClient } from "./client.js";
const ApiClientContext = createContext<ApiClient | null>(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 (
<ApiClientContext.Provider value={client}>
{children}
</ApiClientContext.Provider>
);
}
/**
* Returns the ApiClient from context. Throws if used outside
* <ApiClientProvider>.
*/
export function useApiClient(): ApiClient {
const client = useContext(ApiClientContext);
if (!client) {
throw new Error(
"useApiClient() must be used within an <ApiClientProvider>. " +
"Ensure the root layout wraps the tree with <ApiClientProvider>.",
);
}
return client;
}