useFetch()
- Type
- With Generics
function useFetch(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Promise<any> | undefined;
function useFetch<
E extends EndpointInterface<FetchFunction, Schema | undefined, undefined>,
Args extends readonly [...Parameters<E>] | readonly [null],
>(endpoint: E, ...args: Args): ReturnType<E>;
Great for retrieving resources optimistically before they are needed.
This can be useful for ensuring resources early in a render tree before they are needed.
Expiry Status | Fetch | Returns | Conditions |
---|---|---|---|
Invalid | yes1 | Promise | not in store, deletion, invalidation |
Stale | yes1 | Promise | (first-render, arg change) & expiry < now |
Valid | no | undefined | fetch completion |
no | undefined | null used as second argument |
note
- Identical fetches are automatically deduplicated
React Native
When using React Navigation, useFetch() will trigger fetches on focus if the data is considered stale.
tip
Use in combination with a data-binding hook (useCache(), useSuspense(), useDLE(), useLive()) in another component.
Conditional Dependencies
Use null
as the second argument on any rest hooks to indicate "do nothing."
// todo could be undefined if id is undefined
const todo = useFetch(TodoResource.get, id ? { id } : null);
Example
Simple
function MasterPost({ id }: { id: number }) {
useFetch(PostResource.get, { id });
// ...
}
Conditional
function MasterPost({ id, doNotFetch }: { id: number; doNotFetch: boolean }) {
useFetch(PostResource.get, doNotFetch ? null : { id });
// ...
}
Useful Endpoint
s to send
Resource provides these built-in:
Feel free to add your own RestEndpoint as well.