@svelte-drama/swr

API

swr<ID, DATA>(options) => Model<ID, DATA>

Creates a new Model object. ID must be JSON serializable and DATA must be eligible for structuredClone.

Options

name: string

A name for this model. All models with the same name share a cache.

fetcher: (id: ID) => MaybePromise<DATA>

Your function for retrieving data. Use any library or method you like.

Tip

ID can be anything that is JSON serializable: a string, number, array, or object. Objects will automatically be sorted so that { foo: 1, bar: 2 } and { bar: 2, foo: 1 } are equivalent.

maxAge?: number

Maximum time in milliseconds before data is considered stale. If data is stale, calling get will immediately return any cached data and then perform a background update.

Model<ID, DATA>

Model.clear() => Promise<void>

Removes all data for this model from cache. Note that active subscribers will cause data to be immediately refetched.

Model.delete(id: ID) => Promise<void>

Removes data for a specific id from cache. Note that active subscribers will cause data to be immediately refetched.

Model.keys() => Promise<ID[]>

Returns all ids that are currently in cache for this model.

Model.get(id: ID) => Promise<DATA> & Resource<DATA>

Returns cached data if available, otherwise performs a new fetch. If the cached data is currently stale, a new fetch is performed in the background.

Model.refresh(id: ID) => Promise<DATA>

Refetches data, regardless of its staleness.

Model.set(id: ID, data: DATA) => Promise<DATA>

Sets data

Model.update(id: ID, data: DATA, fn: () => Promise<DATA | void>) => Promise<DATA>

Performs an optimistic update. The updated data will be displayed immediately, but will not be persisted to cache until fn resolves. If fn errors, the update will be rolled back.

Resource<DATA>

Resource objects can be treated as promises. then, catch, and finally all work as expected. Additionally, reactive properties are exposed for non-async work.

Resource.current: DATA | undefined

The data from the most recent successful request. It will be undefined while initially loading data.

Resource.error: any

If the most recent request resulted in an error, it will be preserved here.

Resource.loading: boolean

If there is a network request currently in flight.

For convenience, Resource provides an alias for every function on Model that requires an ID:

  • Resource.delete() => Promise<void>
  • Resource.refresh() => Promise<DATA>
  • Resource.set(data: DATA) => Promise<DATA>
  • Resource.update(data: DATA, fn: () => Promise<DATA | void>) => Promise<DATA>

clearAll() => Promise<void>

import { clearAll } from '@svelte-drama/swr'
clearAll()

Clears all entries from cache and the local database. This is most helpful when a user has been logged out to preserve privacy.