DataHooks
useHttpClient
The client a hook uses: its own client option, else the DataProvider's, else a default same-origin client.
import { useHttpClient } from '@ergasti/bricks';Examples
One client for the app
DataProvider hands an HttpClient to every data hook below it (base URL, CSRF, onUnauthorized), and its language to their messages; without a provider hooks use a same-origin client. This example gives it a pretend server.
Code
import { DataProvider, createHttpClient, useHttpClient, useResource, useDataLanguage } from '@ergasti/bricks';
import { demoServer } from './sample-data';
const client = createHttpClient({
baseUrl: '/api',
fetch: demoServer({ 'GET /api/summary': () => ({ sales: 'EGP 184,300', creators: 304 }) }),
});
function Summary() {
const language = useDataLanguage();
const sameClient = useHttpClient() === client;
const summary = useResource<{ sales: string; creators: number }>('/summary');
return (
<p>
Language {language}; the hook got the provider's client: {String(sameClient)}.{' '}
{summary.status === 'ready' ? `Sales ${summary.data?.sales}, ${summary.data?.creators} creators.` : 'Loading…'}
</p>
);
}
function Provider() {
return (
<DataProvider client={client}>
<Summary />
</DataProvider>
);
}Signature
function useHttpClient(override?: HttpClient | undefined): HttpClientParameters
Prop
Type
Returns
HttpClient
Related
useBricks · DataProvider · useAction · useDataLanguage · useDebouncedCallback · useDrawerResource
Source
src/data/DataProvider.tsx (line 31) on GitHub.