Skip to content

Instantly share code, notes, and snippets.

@dimfeld
Created October 12, 2025 09:40
Show Gist options
  • Select an option

  • Save dimfeld/f51a31a80d41727fe5de97ca10dc5df3 to your computer and use it in GitHub Desktop.

Select an option

Save dimfeld/f51a31a80d41727fe5de97ca10dc5df3 to your computer and use it in GitHub Desktop.
SvelteKit Remote Query Function One-time fetch
This prefetches data to load the service worker cache, without keeping those queries "active", so that
fresh data is loaded when going to a route that uses it.
<script lang="ts">
import { type RemoteQueryFunction } from '@sveltejs/kit';
import { onMount } from 'svelte';
import SingleFetcher from './SingleFetcher.svelte';
import { getData1, getData2, getData3 } from '$lib/queries/mockdata.remote.ts';
interface QuerySet {
queries: RemoteQueryFunction<void, unknown>[];
refreshIntervalMinutes: number;
active: boolean;
timer?: ReturnType<typeof setTimeout>;
}
const querySets: QuerySet[] = $state([
{
queries: [getData1],
refreshIntervalMinutes: 30,
active: false,
},
{
queries: [getData2],
refreshIntervalMinutes: 120,
active: false,
},
{
queries: [getData3],
refreshIntervalMinutes: 1440,
active: false,
},
]);
onMount(() => {
querySets.forEach((querySet) => {
querySet.active = true;
});
return () => {
querySets.forEach((querySet) => {
if (querySet.timer) {
clearTimeout(querySet.timer);
}
});
};
});
</script>
{#each querySets as querySet}
{#if querySet.active}
<SingleFetcher
queries={querySet.queries}
onready={() => {
querySet.active = false;
querySet.timer = setTimeout(
() => {
querySet.active = true;
},
querySet.refreshIntervalMinutes * 60 * 1000
);
}}
/>
{/if}
{/each}
<script lang="ts">
import type { RemoteQueryFunction } from '@sveltejs/kit';
interface Props {
queries: RemoteQueryFunction<void, unknown>[];
onready: () => void;
}
const { queries, onready }: Props = $props();
const instantiated = queries.map((query) => query());
$effect(() => {
if (instantiated.every((q) => q.ready)) {
onready();
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment