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.
- Triggers fetch:
- On first-render
- or parameters change
- or required entity is deleted
- or imperative invalidation triggered
- and When not in cache or result is considered stale
- and When no identical requests are in flight
- and when params are not null
- On first-render
- On Error (404, 500, etc):
- Returned promise will reject
- On fetch returns a promise else undefined.
tip
Use in combination with a data-binding hook (useCache(), useSuspense(), useDLE()) in another component.
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.