useResource
useResource in the Suspense and resources guide.
Two forms:
useResource(fetcher, options?)fetches once, when created.useResource(source, fetcher, options?)fetches when created and again every timesource()changes.sourceis an accessor (or a plain value, which fetches once for that value). While it returnsfalse,nullorundefinednothing is fetched and an in-flight request is aborted. Any other value, including0and"", fetches.
The fetcher gets (info) or (source, info) where info is:
| Field | Meaning |
|---|---|
signal |
An AbortSignal, aborted when a newer fetch starts or the owner is disposed. Pass it to fetch. |
refetching |
true when this call comes from refetch() or from a source change after a value existed. |
value |
The last loaded value, if any. Annotate the parameter ((info: ResourceInfo<User>)) to type it. |
The fetcher runs untracked: signals it reads are not dependencies. Return a promise or a plain value. A plain value is ready at once; a synchronous throw becomes errored.
The handle:
| Member | Meaning |
|---|---|
data() |
The value, or undefined before the first load. Holds the reader's Suspense boundary while the first load is pending. Throws the error when errored. |
data.state |
"unresolved" (nothing fetched yet), "pending" (first load), "ready", "refreshing" (a value exists and a new load is in flight), "errored" |
data.loading |
true while pending or refreshing |
data.error |
The thrown value when errored |
data.latest |
The last successfully loaded value. Never throws, never suspends. |
data.refetch() |
Starts a new load with the current source and keeps the value visible. Returns a promise of the new value; it resolves undefined if the load failed or a newer one replaced it, and never rejects. |
data.mutate(next) |
Replaces the value (or (previous) => next) without fetching, cancels a load in flight, clears the error, and returns the new value. |
Options: initialValue (the resource holds that value from the start and counts as having one, so it never suspends; the first fetch still runs at once, so state is refreshing until it settles), key (names the resource for server rendering, see below), deferStream (on the server, the streamed response holds its first flush until the resource settles, so the value is in the initial HTML; see holding the first flush), name.