Data details
The options, limits and messages behind the Data guide. The signatures are in hamur/app and @hamur/adapter-<library>.
Options of useAsyncData and useFetch
| Option | Meaning |
|---|---|
server | false skips the call on the server; the browser makes it |
lazy | does not block rendering or navigation on this data |
default | a function that returns the value of data while there is no result |
transform | maps the result; the mapped value is stored and sent |
pick | the top-level keys of an object result to keep, after transform |
immediate | false waits for refresh() or execute(); status stays idle |
dedupe | what refresh does while a call is pending: cancel (the default) aborts it and starts again, defer waits for it |
watch | values that call refresh when they change; html has no list. Vue's useFetch also follows its url, query and body; watch: false stops that |
key | useFetch only: the store key, instead of the one made from the URL and the options |
getCachedData | (key, app, { cause }) returns data to use instead of a call, or undefined to call; cause is initial, refresh:manual, refresh:hook (router.refresh(key)) or watch |
- Both return
data,error,status(idle,pending,successorerror),pending,refresh(),execute()(the same function) andclear(). - The key of
useAsyncData(fn, input)is made from the handler and the input. Any other function needs a key first:useAsyncData("comments", () => $fetch("/api/comments")). - Components with the same key share one call.
- The URL,
query,bodyand the key may be getters (in Vue also refs). A new value moves the component to the new key. - The function of a keyed call gets
{ signal }, which aborts when a newer run replaces it, when the entry is cleared and when no component uses the key any more. - After
hamur typegen,useFetch("/api/posts/hello").datahas the type of the handler with thatroute.
import { useAsyncData, useFetch } from "@hamur/adapter-react"
interface Comment {
id: number
text: string
}
export default function Comments({ postId }: { postId: string }) {
const { data, status, refresh } = useFetch<Comment[]>(`/api/posts/${postId}/comments`, { default: () => [] })
const count = useAsyncData("comment-count", async () => (data ?? []).length, { server: false })
return (
<section>
<p>{status === "pending" ? "Loading" : `${count.data ?? 0} comments`}</p>
<ul>
{data?.map((comment) => (
<li key={comment.id}>{comment.text}</li>
))}
</ul>
<button type="button" onClick={() => void refresh()}>
Reload
</button>
</section>
)
}
Keep data between pages
An entry is dropped when no component on screen uses its key, so a page visited again loads again. Return the entry from getCachedData to keep it:
import { useFetch, useRoute } from "@hamur/adapter-react"
export default function Author() {
const route = useRoute()
const { data } = useFetch<{ name: string }>(() => `/api/authors/${route.params.id}`, {
getCachedData: (key, app) => app.asyncData.get<{ name: string }>(key)?.data,
})
return <p>{data?.name}</p>
}
clearAsyncData(app, key?) of hamur/app empties entries, as on logout (clearAsyncData).
Server rendering
| Library | How the server waits for the data |
|---|---|
| React | the component suspends while the call runs |
| Vue, Angular | the render waits for the call |
| Solid, Preact, Svelte, html | the render is repeated until the data has arrived |
- In React, a component behind
Suspensecannot change the status of the response: the first part of the page has been sent. Use aloadfor that. - A
useFetchof a URL that starts with/is answered in process, with the request'scookieandauthorizationheaders. A URL with a host gets neither. - A
set-cookieof such an in-process answer is added to the page's response, and later calls of the same request send the cookie. No other header is copied.
Errors in production
error is what you threw with createError, with its status, message and data. Any other error becomes a 500 Internal Server Error without data, or keeps its own HTTP status with that status's text. The original is in the server log.
load
The context is listed under Loader, with what differs in the browser under SharedLoaderContext. The types of one page are its route types.
| Case | What happens |
|---|---|
| a handler sets a status or a cookie, or throws | on the server it shares the page's request, so the page gets that status, cookie, error or redirect |
redirect(to) returned or thrown | the visitor goes to to; another origin needs redirect(to, { external: true }) |
| any other throw | the error page |
| a value that cannot be serialized | the request fails with a 500. The server log names the path, such as payload.data["posts-id"].post.save |
| a static site | hamur generate writes the data at build time, and the browser never runs the load |
Parent loads
parent() is the data of the nearest parent route with a load, or undefined.
import type { Load } from "hamur/app"
import { listOrders } from "#server"
export const load = (async ({ parent }) => {
const { account } = await parent<{ account: { name: string } }>()
return { orders: await listOrders({ owner: account.name }) }
}) satisfies Load
N routes that each await parent() make N requests in a row in the browser. One handler that returns everything makes one:
import type { Load } from "hamur/app"
import { getDashboard } from "#server"
export const load = (async () => ({ summary: await getDashboard() })) satisfies Load
Layouts
- A layout's
loadstarts with the loads of the page, andctx.routeis the matched page. - It keeps its data between two pages with the same layout while the params and the query (or its
searchKeys) stay the same.router.refresh()runs it again. - The
loadof the first page with no parentloadabove it gets the layout's data fromparent(). The page's ownuseData()never has it.
searchKeys and search
ctx.query,ctx.searchandctx.url.searchhold only the keys insearchKeys.- It must be an array literal of string literals, else the build fails with HAMUR_E1025.
- A page's
searchschema checks the whole query, so a key it requires must be insearchKeys.
Fill useAsyncData from a load
prime(fn, input, value) stores the answer that useAsyncData(fn, input) will read, so the handler does not run twice. prime(key, value) does the same for a keyed call. When two loads prime one key, the innermost route wins, and hamur dev logs both names.
import type { Load } from "hamur/app"
import { getPost } from "#server"
export const load = (async ({ params, prime }) => {
const id = params.id as string
prime(getPost, { id }, await getPost({ id }))
return {}
}) satisfies Load
import { useAsyncData, useRoute } from "@hamur/adapter-react"
import { getPost } from "#server"
export default function Post() {
const { id } = useRoute().params
const { data, error, status } = useAsyncData(getPost, () => ({ id: id as string }))
if (error) return <p role="alert">{error.message}</p>
if (!data) return <p>{status === "pending" ? "Loading" : ""}</p>
return (
<article>
<h1>{data.title}</h1>
<p>{data.body}</p>
</article>
)
}
serialization
Export serialization from the load file to choose what goes into the page. The server's HTML is the same either way.
serialization | Effect |
|---|---|
"always" (the default) | the data is in the page |
"auto" | the data is in the page when its serialized text has at most 8192 characters |
"never" | the data is not in the page; the browser runs the load before it hydrates |
Any other value fails the request: serialization of route "feed" must be "always", "never" or "auto", got "sometimes". A meta.ssr: false page and a "never" page are still written in full into the payload file of a static build.
Values in the payload
Besides JSON values, these arrive as they were: Date, RegExp, URL, BigInt, Map, Set, typed arrays, errors, and repeated or circular references. What useData() returns is read-only; copy it into local state to change it on the page.
Your own types
app/transport.ts teaches the payload a class. It also covers the payload file and the inputs and answers of handlers:
import type { Transport } from "hamur/app"
export class Money {
constructor(
readonly cents: number,
readonly currency: string,
) {}
}
export const transport = {
Money: {
encode: (value) => value instanceof Money && [value.cents, value.currency],
decode: ([cents, currency]) => new Money(cents, currency),
},
} satisfies Transport
An app plugin can register one too, for the page payload only. This is app/plugins/tag.ts:
import { definePayloadReducer, definePayloadReviver, definePlugin } from "hamur/app"
export class Tag {
constructor(readonly name: string) {}
}
export default definePlugin((app) => {
definePayloadReducer(app, "Tag", (value) => value instanceof Tag && value.name)
definePayloadReviver(app, "Tag", (name: string) => new Tag(name))
})
encode returns false for a value that is not its type. The messages are under Transport.
Refresh keys
| Call or key | What it does |
|---|---|
router.refresh() | runs every load of the page and every useAsyncData on screen; adds no history entry and does not scroll |
router.refresh(key), or a list | runs the load files that declared a key, layouts included, and the useAsyncData entries of that key |
router.refresh(fn, input) | refreshes the entry of one handler |
ctx.depends(...keys) | declares keys, any strings. Handler calls are not recorded, so name them here |
ctx.fetch(url) | declares its URL: an app path with its query and without app.baseURL, any other URL as its href |
ctx.untrack(fn) | records nothing that fn calls before its first await |
a key without ? | also matches that URL with any query: /api/posts matches /api/posts?page=2, not /api/posts/1 |
| a key that nothing declared | does nothing |
Calls in the same tick share one run, and a call during a navigation waits for it. A page that exports shouldRefresh can keep its data. usePoll refreshes on a timer.
The client data cache
The browser keeps the data of the load files it ran, by route, params and query (only the searchKeys when there are some).
| Setting | Default | Meaning |
|---|---|---|
app.data.staleTime or meta.staleTime | 0 | milliseconds an entry is shown without running its load; the innermost page's meta wins |
app.data.gcTime or meta.gcTime | 300000 | milliseconds until an entry that is no longer on screen is deleted |
app.data.staleReload | "blocking" | "background" shows a stale entry at once and runs the load after the navigation |
app.data.refreshOnFocus | false | a number of milliseconds: refresh() when the tab becomes visible, at most once in that time |
app.data.refreshOnReconnect | false | true calls refresh() when the browser is online again |
- Back and forward show the data the entry showed, under the same rule.
- The cache holds 100 entries.
- A fresh entry skips the
load, and with it any redirect or check inside. The handlers still check every call. - Every entry is dropped by
router.refresh(), a successfuluseActionorFormcall of a non-GEThandler (unless it setsrefresh: false), a non-GET$fetch, a GraphQL mutation and a cookie change.refresh(key)drops the entries with that key. - It is off on a static site, where each navigation reads the payload file.
With experimental.offlineRetry: true, a navigation, a prefetch or a useFetch that failed on the network waits for the browser to be online. It tries again after 1, 2, 4 … 30 seconds, for up to 5 minutes. Only GET and HEAD calls are tried again.
entries
The build calls entries once and writes one page for each set of params. The types are under Entries.
| Case | Rule |
|---|---|
| the params of a set | a string for :id, a string or undefined for :id?, a string array for **:path |
a child of a page that has entries | called once for each parent set, as entries({ parent }); returns only its own params |
dynamicParams = true (the default) | a path that is not listed renders on request |
dynamicParams = false | a path that is not listed answers 404 Page Not Found: /posts/c, also in the browser, and the build does not follow links to it. On the static preset the host's 404.html answers |
| the browser's code | has neither export, nor the imports only they used |
prerender: false, prerender.ignore | win over a set |
A file may export entries without a load. The build logs Prerender entries of /posts/:id: /posts/hello, /posts/second. A page that no set and no link reaches is reported by prerender.onUnseenRoutes (Route rules).
| Mistake | Build error |
|---|---|
| a missing param | entries of app/pages/blog/[slug].load.ts returned an entry without "slug" |
| an unknown param | entries of app/pages/blog/[slug].load.ts returned "slg", which /blog/:slug does not have |
| a value of the wrong type | entries of app/pages/blog/[slug].load.ts returned "slug": 3; a param is a string |
| a matcher refuses a value | entries of app/pages/items/[id=integer].load.ts returned "id": "x", which the matcher "integer" refuses |
| not an array | entries of app/pages/blog/[slug].load.ts must return an array of params (got object) |
| a page without params | HAMUR_E1048 |
| the Next.js name | HAMUR_E1072 |
dynamicParams that is not a literal | HAMUR_E1026 |
dynamicParams without entries | HAMUR_E1073 |
Prerender a page without params
meta.rulesis a route rule for the page's own path. A rule inhamur.config.tson the same pattern wins over it.- There is no
meta.prerender: it fails with HAMUR_E1051. - On a server preset,
prerender.staticPages: truewrites every page whose layouts, parents and page have noload.