svelte-rune-swr
v1.0.5
Published
porting of vue swr https://github.com/Kong/swrv use svelte 5 with runes
Readme
svelte-rune-swr
porting of vue swr https://github.com/Kong/swrv use svelte 5 with runes
Usage
<script>
const { swr } = useSWR('https://api.sampleapis.com/coffee/hot', async (url) => {
return await fetch(url).then((res) => res.json());
});
const { data, isValidating, error } = $derived(swr);
</script>
<div class="demo">
{#if !data}
<div>Loading ...</div>
{:else}
<div>
Message: {data.message}
</div>
{#if isValidating}
<div>Refreshing...</div>
{/if}
{/if}
</div>QA
why it don't have isLoading
Just check if the data is valid — even if the request is still running, you still have data on the cache to display
how do change key and make it reactive
// ❌ not working
const { swr }= useSWR(`https://api.sample.com/${page}`, fetch)
// ✅ working
const { swr } = useSWR(()=>`https://api.sample.com/${page}`, fetch)
You can manual change the fetcher by mutate function
const {swr, mutate}= useSWR(`https://api.sample.com/${page}`, fetch)
mutate((url)=> { })working with streaming data from load function
You need to set invalidateAll for onBeforeRevalidate so that it can load a trigger load data on revalidate
import { invalidateAll } from '$app/navigation';
let { data } = $props();
const { swr, mutate } = useSWR('/ssr', () => data.post, {
onBeforeRevalidate: () => invalidateAll()
});
const { data: post, isValidating } = $derived(swr);
use localstore
for request not change it
import LocalStorageCache from "svelte-rune-swr/adapters/localStorage";
const { swr } = useSWR(() => `post${page}`, loadPost, {
cache: new LocalStorageCache(),
revalidateOnFocus: false,
}