Reference › APIs

On this page

clarusjs/fetch

Data an island fetches itself, in the browser. For the how-to with a live dashboard, see Fetching data.

ts
import { resource, batch, json } from 'clarusjs/fetch'

resource() #

ts
resource<T>(fetcher, options?): Resource<T>

Runs fetcher and gives its answer as value, loading and error. It runs again when a signal the fetcher reads changes.

Parameters #

Returns #

A Resource<T>:

Caveats #

Usage #

Show loading, error and data:

tscl
<script>
  import { json, resource } from 'clarusjs/fetch'
  const user = resource(({ signal }) => json('/api/me', { signal }))
</script>
@if (user.value) { <p>{{ user.value.name }}</p> }
@else if (user.error) { <p>Couldn't load. <button (click)="user.refetch()">Retry</button></p> }
@else { <p>Loading…</p> }

Wait for another resource (a chain):

ts
const members = resource(({ signal }) => team.value && json(`/api/teams/${team.value.id}/members`, { signal }))

Write it with async/await:

ts
const members = resource(async ({ signal }) => {
  const id = team.value?.id
  if (id === undefined) return            // not ready: resolves to undefined
  const res = await fetch(`/api/teams/${id}/members`, { signal })
  if (!res.ok) throw new Error(`members: ${res.status}`)
  return res.json()
})

Follow a state (a page number, a search box):

ts
let page = state(1)
const results = resource(({ signal }) => json(`/api/items?page=${page}`, { signal }))

Poll, and retry a flaky endpoint:

ts
const prices = resource(load, { retry: 3, refetch: { interval: 10_000 } })

Start from the server's data:

ts
const stats = resource(load, { initial: props.stats })

Wait for the data in code:

ts
async function exportCsv() {
  const rows = await items.ready()   // the first answer, fetched or already there
  download(toCsv(rows))
}

Update optimistically, then confirm:

ts
async function rename(name) {
  user.mutate({ ...user.value, name })
  await fetch('/api/me', { method: 'PATCH', body: JSON.stringify({ name }) })
  await user.refetch()
}

Caching #

With key, a resource's answers live in a cache shared by the whole page.

invalidate() #

ts
invalidate(prefix?: unknown[]): void

Marks every cached answer whose key starts with prefix as stale. The resources showing one fetch it again now; the others fetch when next used.

Parameters #

Caveats #

Usage #

ts
async function rename(id, name) {
  await fetch(`/api/items/${id}`, { method: 'PATCH', body: JSON.stringify({ name }) })
  invalidate(['items'])
}

setData() #

ts
setData<T>(key: unknown[], value: T | ((prev: T | undefined) => T)): void

Sets a cached answer, and shows it in every resource using that key. Creates the entry if it's missing.

Usage #

An optimistic edit, confirmed by the server:

ts
async function rename(id, name) {
  setData(['items', { page }], (data) => data && { ...data, rows: data.rows.map((r) => (r.id === id ? { ...r, name } : r)) })
  try {
    await fetch(`/api/items/${id}`, { method: 'PATCH', body: JSON.stringify({ name }) })
  } finally {
    invalidate(['items']) // the server's version wins, also if the request failed
  }
}

prefetch() #

ts
prefetch<T>(key: unknown[], fetcher): Promise<void>

Fetches an answer into the cache ahead of time, unless it's there and not invalidated (a resource's stale isn't considered here). The promise settles when it's stored. Errors are ignored: the resource that opens the key later fetches again.

Usage #

The next page, while this one is shown:

ts
effect(() => {
  if (list.value && page < list.value.pages)
    prefetch(['records', { page: page + 1 }], ({ signal }) => json(`/api/records?page=${page + 1}`, { signal }))
})

batch() #

ts
batch<T>(load, options?): { get(key): Promise<T> }

Sends the keys asked at the same moment as one request, from any island on the page.

Parameters #

Returns #

{ get(key) }. get returns a promise of that key's answer.

Caveats #

Usage #

ts
// src/stores/stats.ts: shared, so every card on the page joins the same request
export const stats = batch((keys, { signal }) => json(`/api/stats?keys=${keys.join(',')}`, { signal }))
ts
// in each card's script
const stat = resource(() => stats.get(key))

json() #

ts
json<T = any>(url, init?): Promise<T>

fetch(url, init), then the response's JSON. A response that isn't 2xx throws an Error naming the URL and the status (/api/me: 503 Service Unavailable), with the code in its status property, so retry and error see it (if (user.error?.status === 404) …). T defaults to any, as Response.json() does.

ts
const me = resource(({ signal }) => json<User>('/api/me', { signal }))