Getting Started
@svelte-drama/swr deduplicates requests across both components and different browser tabs. It implements a “stale-while-revalidate” strategy, so data is immediately available while updates are performed in the background.
Installation
npm install --save @svelte-drama/swr Defining a Model
import { swr } from '@svelte-drama/swr'
const Model = swr({
name: 'model-name',
async fetcher(id: number) {
const request = await fetch(`/your-api/${id}`)
return request.text()
},
}) name uniquely identifies a model. Models sharing a name also share a cache.
fetcher can be any function that accepts a single argument (string, number, array, or object) and returns your data. That argument is JSON serialized and used as a cache key.
Fetching
Important
This example requires Svelte’s experimental async support to be enabled via compilerOptions.
const value = $derived(await Model.get(id)) The first request for a given id calls your fetcher function and caches the result. Subsequent calls will be served from cache, regardless of whether they come from another component, a new page load, or a different tab.
Updating Data
To set a new value:
const data = await yourUpdateFunc()
Model.set(id, data) To perform an optimistic update:
Model.update(id, new_data, yourUpdateFunc) The value will be updated immediately. However, this is not persisted to the cache or broadcast to other tabs until yourUpdateFunc resolves. If yourUpdateFunc errors, then the value will automatically be reverted.