Skip to main content

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.

beginneruseFetchpollingtypescript
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" });
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/provider-defaults hyper-fetch-react-provider-defaults && cd hyper-fetch-react-provider-defaults && npm install && npm run dev
What it shows
  1. <Provider config> sets default options for every useFetch below it with useFetchConfig.
  2. Hook options win: an option passed to useFetch replaces the default of the same name and keeps the others.
  3. Live config: when the config prop changes, the hooks pick up the new values on the next render.
  4. Request counters on each widget show how the options change the traffic.

How it works​

  1. App.tsx keeps the defaults in state and passes them to the provider:

    const config: ProviderOptionsType = { useFetchConfig: defaults };
    <Provider config={config}>...</Provider>;

    ProviderOptionsType types the object, so a misspelled option is a compile error.

  2. QuoteWidget calls useFetch(getRandomQuoteRequest) with no options. It refreshes every few seconds and on window focus because the provider says so.

  3. TodoWidget passes { refreshTime: 2000 }. The hook merges its options over the provider's, one option at a time, so refresh and refetchOnFocus still come from the provider.

  4. UserWidget passes { refresh: false, refetchOnFocus: false }. A profile rarely changes, so it loads once.

  5. Each widget counts its requests with the hook's onRequestStart callback. Turn refresh off and the quote and the todo stop updating.

  6. api.ts has 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.

When to use it
  • 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 Provider around it. It replaces the outer config, it does not merge with it.
  • Keep request settings like retry or staleTime on the request or the client. The provider sets hook options only.

Summary

<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.