useFetch
The useFetch hook is used for data fetching. It works on the client as well as on the server. The data that is fetched on the server will be transferred to the client.
import { useFetch } from '@archibald/client';
const RETURN_VALUE = useFetch<DATA_TYPE>(PARAMETERS);
Besides the positional signature useFetch(key, action, options), the hook also accepts a single options object that combines the key, the action callbacks and the fetch options:
const RETURN_VALUE = useFetch<DATA_TYPE>({
key: ['product', id],
data: async ({ request }) => request.get(`/products/${id}`),
// ...any FetchOptions
ssr: false
});
The object form (FetchMaxOptions<T>) is FetchOptions & DataOptions<T> & { key: FetchKey } — i.e. key is required, the action lives in the data / before / after fields and all fetch options sit on the same object.
If your component cannot render without the data, prefer useSuspenseFetch. It always suspends and always throws errors to the nearest error boundary, so its data is guaranteed present and you can drop the isLoading / isError branches. Both hooks share the same request handling, so a key is fully interchangeable between them.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | FetchKey | ✔️ |
|
| action | DataFunctionType<DATA_TYPE> | ✔️ |
|
| options | FetchOptions |
|
key
The key can be of type string, number or null, or an array of these types.
The key can also be an object of type KeyObject. The KeyObject object has the following properties:
| Name | Type | Description |
|---|---|---|
| key | KeyType | The key as described above. |
| group | string | boolean | A group to be used as fallback by the useFetch hook. |
action
An action can be a function or an object.
Passing a function as the action
- Type:
DataFunction<DATA_TYPE>
The callback function passed to the useFetch hook receives an object of type DataFunctionParams that provides following properties:
| Property | Type | Description |
|---|---|---|
| client | DataClient | The DataClient instance. |
| isServer | boolean | Returns true when the data fetching takes place on the server. |
| isFirstRender | boolean | Returns true on the first render. |
| request | DataRequest | The DataRequest instance. |
| willFetch | boolean | Returns true if the data fetching will take place. |
| signal | AbortSignal | Abort signal for this fetch run. It aborts when the run is superseded by a newer one for the same key, when the entry is deleted, or when the client is destroyed. Forward it into your request (e.g. api.createRequest({ url, signal })) to cancel the in-flight network call — a run that rejects because its signal aborted is treated as cancelled, not as an error. |
Passing an object as the action
- Type:
DataOptions<DATA_TYPE>
The DataOptions object has the following properties: More Info...
| Property | Type | Description |
|---|---|---|
| after | VoidFunction |
|
| before | VoidFunction |
|
| data | DataFunction | See Passing a function as the action section for reference. |
The data, before and after callbacks do not need to be memoized to keep the request stable. useFetch reads the latest closure you pass on every invocation, so changing the action function between renders (for example, one that closes over changed props or state) is reflected in the cache and the UI without recreating the underlying request or re-triggering a fetch. The key still controls when a refetch happens.
Options
- Type:
FetchOptions
The FetchOptions object has the following properties:
| Name | Type | Default | Description |
|---|---|---|---|
| clearOnRefetch | boolean | true | Defines if the cache entry should be deleted before being refetched. More Info... |
| enabled | boolean | true |
|
| enableOnlyWhenAllKeysTruthy | boolean | false | If true, the action will only be executed when all keys resolve to true. More Info... |
| error | number | 5 seconds | Defines how long an error is kept in the cache. More Info... |
| errorBoundary | boolean | false | Defines if the error should be thrown. The suspense property has to be true in order for this to work. More Info... |
| poll | number | 0 | Reexecute the action in the provided time interval. More Info... |
| refetch | number | 5 minutes |
|
| refetchAfterFocus | boolean | false | Reexecute the action when the window regains focus. More Info... |
| refetchAfterHydrate | boolean | false | Reexecute the action after the component has been hydrated. More Info... |
| ssr | boolean | true | If false, the action will only be executed on the client. More Info... |
| suspendAfterFirstLoad | boolean | false | If true, the hook only suspends once the request has loaded at least once (or the component has rendered before). When absent, every pending fetch suspends. More Info... |
| suspense | boolean | true | If true, the useFetch hook will use suspense mode. More Info... |
| ttl | number | 15 minutes |
|
| enduring | boolean | false | If true the cache entry persists throughout automatic cache cleanups after the DataClient cache has reached the maximal amount of entries. More Info... |
Return value
- Type:
FetchResult
The FetchResult object has the following properties:
| Property | Type | Description |
|---|---|---|
| data | DATA_TYPE | null | The data that was retrieved through the hook. This value can be typed by passing a type to the hook. Its reference is kept stable across refetches that return structurally identical data — see structural sharing. |
| error | DefaultResponseError | null | The error that was returned in the action. |
| isLoading | boolean | Indicates if the data is being loaded. |
| isDone | boolean | Returns true when the data is finished loading. |
| isError | boolean | Returns true when the request got an error. |
| isPrefetched | boolean | Returns true when the data was prefetched on the server. |
| isStale | boolean | Returns true when the data was retrieved from cache. |
| resetError | Function | Manually clear the error state from the cache and local state. More Info... |
| refetch | Function | Re-execute the action. |
| request | DataRequest | The DataRequest instance. |
| prefetch | Function | Executes the useFetch hook and puts the data in the cache. The data is not returned. |
See also
- useSuspenseFetch — the Suspense-first variant with non-null
data. - suspense — how the suspense seam works step by step.
- structural sharing — referential stability of
dataacross refetches.