Skip to content

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

OptionMeaning
serverfalse skips the call on the server; the browser makes it
lazydoes not block rendering or navigation on this data
defaulta function that returns the value of data while there is no result
transformmaps the result; the mapped value is stored and sent
pickthe top-level keys of an object result to keep, after transform
immediatefalse waits for refresh() or execute(); status stays idle
dedupewhat refresh does while a call is pending: cancel (the default) aborts it and starts again, defer waits for it
watchvalues that call refresh when they change; html has no list. Vue's useFetch also follows its url, query and body; watch: false stops that
keyuseFetch 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, success or error), pending, refresh(), execute() (the same function) and clear().
  • 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, body and 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").data has the type of the handler with that route.
tsx
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:

tsx
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

LibraryHow the server waits for the data
Reactthe component suspends while the call runs
Vue, Angularthe render waits for the call
Solid, Preact, Svelte, htmlthe render is repeated until the data has arrived
  • In React, a component behind Suspense cannot change the status of the response: the first part of the page has been sent. Use a load for that.
  • A useFetch of a URL that starts with / is answered in process, with the request's cookie and authorization headers. A URL with a host gets neither.
  • A set-cookie of 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.

CaseWhat happens
a handler sets a status or a cookie, or throwson the server it shares the page's request, so the page gets that status, cookie, error or redirect
redirect(to) returned or thrownthe visitor goes to to; another origin needs redirect(to, { external: true })
any other throwthe error page
a value that cannot be serializedthe request fails with a 500. The server log names the path, such as payload.data["posts-id"].post.save
a static sitehamur 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.

ts
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:

ts
import type { Load } from "hamur/app"
import { getDashboard } from "#server"

export const load = (async () => ({ summary: await getDashboard() })) satisfies Load

Layouts

  • A layout's load starts with the loads of the page, and ctx.route is 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 load of the first page with no parent load above it gets the layout's data from parent(). The page's own useData() never has it.
  • ctx.query, ctx.search and ctx.url.search hold only the keys in searchKeys.
  • It must be an array literal of string literals, else the build fails with HAMUR_E1025.
  • A page's search schema checks the whole query, so a key it requires must be in searchKeys.

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.

ts
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
tsx
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.

serializationEffect
"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:

ts
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:

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 keyWhat 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 listruns 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 declareddoes 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).

SettingDefaultMeaning
app.data.staleTime or meta.staleTime0milliseconds an entry is shown without running its load; the innermost page's meta wins
app.data.gcTime or meta.gcTime300000milliseconds 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.refreshOnFocusfalsea number of milliseconds: refresh() when the tab becomes visible, at most once in that time
app.data.refreshOnReconnectfalsetrue 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 successful useAction or Form call of a non-GET handler (unless it sets refresh: 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.

CaseRule
the params of a seta string for :id, a string or undefined for :id?, a string array for **:path
a child of a page that has entriescalled 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 = falsea 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 codehas neither export, nor the imports only they used
prerender: false, prerender.ignorewin 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).

MistakeBuild error
a missing paramentries of app/pages/blog/[slug].load.ts returned an entry without "slug"
an unknown paramentries of app/pages/blog/[slug].load.ts returned "slg", which /blog/:slug does not have
a value of the wrong typeentries of app/pages/blog/[slug].load.ts returned "slug": 3; a param is a string
a matcher refuses a valueentries of app/pages/items/[id=integer].load.ts returned "id": "x", which the matcher "integer" refuses
not an arrayentries of app/pages/blog/[slug].load.ts must return an array of params (got object)
a page without paramsHAMUR_E1048
the Next.js nameHAMUR_E1072
dynamicParams that is not a literalHAMUR_E1026
dynamicParams without entriesHAMUR_E1073

Prerender a page without params

  • meta.rules is a route rule for the page's own path. A rule in hamur.config.ts on the same pattern wins over it.
  • There is no meta.prerender: it fails with HAMUR_E1051.
  • On a server preset, prerender.staticPages: true writes every page whose layouts, parents and page have no load.