Provider defaults
Three widgets that refresh themselves. The refresh options are set once in the Provider, not in every hook. One widget
uses them as they are, one changes the interval and one opts out. The switches at the top change the defaults while the
app runs.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type Quote = { id: number; quote: string; author: string };
export type Todo = { id: number; todo: string; completed: boolean };
export type User = {
id: number;
firstName: string;
lastName: string;
email: string;
};
/** The requests know nothing about refreshing. That is hook behavior, set once in the Provider. */
export const getRandomQuoteRequest = client.createRequest<{
response: Quote;
}>()({
endpoint: "/quotes/random",
});
export const getRandomTodoRequest = client.createRequest<{ response: Todo }>()({
endpoint: "/todos/random",
});
export const getUserRequest = client
.createRequest<{
response: User;
queryParams: { select: string };
}>()({ endpoint: "/users/:userId" })
.setParams({ userId: 1 })
// `select` is a dummyjson query param: the API returns only these fields.
.setQueryParams({ select: "firstName,lastName,email" });
npx tiged BetterTyped/hyper-fetch/examples/react/provider-defaults hyper-fetch-react-provider-defaults && cd hyper-fetch-react-provider-defaults && npm install && npm run dev<Provider config>sets default options for everyuseFetchbelow it withuseFetchConfig.- Hook options win: an option passed to
useFetchreplaces the default of the same name and keeps the others. - Live config: when the
configprop changes, the hooks pick up the new values on the next render. - Request counters on each widget show how the options change the traffic.
How it works
-
App.tsxkeeps the defaults in state and passes them to the provider:const config: ProviderOptionsType = { useFetchConfig: defaults };<Provider config={config}>...</Provider>;ProviderOptionsTypetypes the object, so a misspelled option is a compile error. -
QuoteWidgetcallsuseFetch(getRandomQuoteRequest)with no options. It refreshes every few seconds and on window focus because the provider says so. -
TodoWidgetpasses{ refreshTime: 2000 }. The hook merges its options over the provider's, one option at a time, sorefreshandrefetchOnFocusstill come from the provider. -
UserWidgetpasses{ refresh: false, refetchOnFocus: false }. A profile rarely changes, so it loads once. -
Each widget counts its requests with the hook's
onRequestStartcallback. Turn refresh off and the quote and the todo stop updating. -
api.tshas no refresh settings. How often to refetch is a choice of the screen, not of the endpoint, so it lives in hook options.
The order is: built-in defaults, then the provider's useFetchConfig, then the options passed to the hook. Options
passed as undefined are skipped, so forwarding an optional prop does not erase a default. The provider has the same
kind of key for the other hooks: useSubmitConfig, useCacheConfig, useQueueConfig and more.
- App-wide behavior such as refetching on focus or reconnect, or a standard debounce time.
- Different defaults for one part of the app: nest a second
Provideraround it. It replaces the outer config, it does not merge with it. - Keep request settings like
retryorstaleTimeon the request or the client. The provider sets hook options only.
Related
<Provider config={{ useFetchConfig }}> sets the starting options for every useFetch in the tree. A hook overrides
only the options it passes, so most components need no options at all.
