SWR
Goal: SWR in a React page, with its first data coming from the page's load and its cache refreshed after a change. The runnable sample is examples/data-react/; swr is a devDependency of that example, and Hamur has no module for it.
When Hamur's own data is enough: useAsyncData(handler, input) reads, useAction or Form changes and refreshes the page, and router.refresh(key) re-runs what depends on a key (Data). Reach for SWR when you want its cache by key across components, revalidation on focus and reconnect per key, or its small API on top of an existing fetcher. A handler is the function both call.
- Give SWR a cache for each request. Its default cache is a module-level
Map, which every request on the server would share.SWRConfigwithprovider: () => new Map()makes a fresh one when it mounts, so put it in the root component (app/app.tsx, Root component):
import { useState } from "react"
import { Outlet } from "@hamur/adapter-react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { SWRConfig } from "swr"
export default function App() {
const [queryClient] = useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>
<SWRConfig value={{ provider: () => new Map() }}>
<Outlet />
</SWRConfig>
</QueryClientProvider>
)
}
- Seed the hook from the page's
load. Theloadcalls the handler, so the server render and the first browser render have the data, and it is in the page payload (What goes into the payload). SWR does not fetch while the server renders, so giveuseSWRthe data asfallbackData. WithrevalidateIfStale: falseit does not fetch again when the page mounts either:
import type { Load } from "hamur/app"
import { listTodos } from "#server"
export const load = (async () => ({ todos: await listTodos() })) satisfies Load
import { useState } from "react"
import { useData } from "@hamur/adapter-react"
import useSWR from "swr"
import type { Todo } from "../../shared/todo.ts"
import { addTodo, listTodos } from "#server"
export default function Todos() {
const { todos: seed } = useData<{ todos: Todo[] }>()
const [title, setTitle] = useState("")
const { data, mutate } = useSWR("todos", () => listTodos(), { fallbackData: seed, revalidateIfStale: false })
return (
<main>
<h1>SWR</h1>
<ul>
{data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<form
onSubmit={async (event) => {
event.preventDefault()
await addTodo({ title })
setTitle("")
await mutate()
}}
>
<input value={title} onChange={(event) => setTitle(event.target.value)} />
<button>Add</button>
</form>
</main>
)
}
The fetcher is the handler. In the browser a call is a request; the key "todos" is only the name of the cache entry.
Refresh after a change. The page calls the handler and then
mutate(), the bound functionuseSWRreturns, which revalidates the key. A handler called this way does not go throughuseAction, so Hamur does not read the page again; the SWR cache is the one you refresh. For one key across the app,useSWRConfig().mutate(key)does the same.Know which copy wins.
fallbackDatais used while the key has no data in the cache. After the first fetch or amutate(), the cache has the data and a laterloaddoes not replace it. Navigating away and back keeps the entry, andrevalidateIfStale: falsekeeps it without a request until you callmutate()or set arefreshInterval.
See also: Data, Handlers, TanStack Query, Hydration.