@svelte-drama/swr

Promise based data caching built just for Svelte

Automatic Caching

Data is cached based on the key you supply.

const User = swr({
	name: 'user',
	maxAge: 30_000,
	async fetcher(user_id) {
		const request = await fetch(`/user/${user_id}`)
		return request.json()
	},
})

Deduplicate Requests

Requests deduplicated across components, visits, and tabs.

// Profile.svelte
const user = User.get(10)

// TopNav.svelte
const user = User.get(10)

Promise Based

Integrate seamlessly with top level await, {#await}, and <svelte:boundary>.

<script>
import { User } from '#lib'
let { id } = $props()
const user = $derived(await User.get(id))
</script>

Welcome, {user.name}!

Optimistic Updates

Changes are applied immediately, with automatic rollbacks on error.

import { saveUser } from 'your-api'

user.update({ name: 'NEW NAME' }, (value) => {
	return saveUser(value)
})