Data loading
Export a data() function and its result appears as ctx.data in your render function. It runs at build time, and per-request in the dev server.
export async function data({ params, dev }) {
const res = await fetch(`https://api.example.com/posts/${params.slug}`)
return await res.json()
}
export default ({ data }) => `
<html><body>
<h1>${data.title}</h1>
${data.body}
</body></html>
`import { html, body, h1 } from 'javascript-to-html'
export async function data({ params, dev }) {
const res = await fetch(`https://api.example.com/posts/${params.slug}`)
return await res.json()
}
export default ({ data }) =>
html(
body(
h1(data.title),
data.body,
),
)export async function data({ params, dev }) {
const res = await fetch(`https://api.example.com/posts/${params.slug}`)
return await res.json()
}
export default function Post({ data }) {
return (
<html>
<body>
<h1>{data.title}</h1>
<div dangerouslySetInnerHTML={{ __html: data.body }} />
</body>
</html>
)
}fetchWithCache
Building many pages against the same API? Import fetchWithCache from sitelo:
import { fetchWithCache } from 'sitelo'
export async function data({ params }) {
const res = await fetchWithCache(
`https://api.example.com/posts/${params.slug}`,
{ /* standard fetch options */ },
{ maxAge: 3600 }
)
return { post: await res.json() }
}Options
maxAge— cache TTL in seconds (default3600)cacheKey— custom key (default: hash of URL + method + headers + body)forceRefresh— bypass the cachecache—'auto'|'memory'|'fs'|'none'
Cache modes
auto(default) — memory in dev, filesystem in production buildsmemory— in-process, cleared when the process exitsfs— persisted undernode_modules/.cache/none— always fetch
Only GET requests are cached by default (pass a cacheKey to cache other methods). Error responses are never cached.