DEV Community

Jonathan Gamble
Jonathan Gamble

Posted on Edited on

Async Fetching in Svelte 5

When you want to fetch something in Svelte, the recommended method is to put it in the load function.

I wrote an article about async fetching and why this could be important to work outside the load function.

Generally speaking, when SSR is not involved, you have better control of race conditions, error handling, and implementation outside the load function. While I agree in MOST situations you should use the load functions (with SvelteKit), this is not true for ALL situations.

Here is a simple resource function to handle this:

// resource.svelte.ts

export let resource = <T>(
    fn: () => Promise<T>,
    initialValue?: T
) => {

    const _rune = $state<{ value: T | undefined }>({
        value: initialValue
    });

    $effect(() => {
        fn().then((data) => {
            _rune.value = data;
        });
    });

    return _rune;
};
ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025 ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025

And you would use it like so in your component:

import { resource } from '$lib/resource.svelte';
...
const todo = resource<Todo>(() =>
  fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
    .then((response) => response.json())
);
ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025 ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025

And show the value with:

{todo.value}
ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025 ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025

Similar Concepts in Other Frameworks

Now you can easily create a signal from an async resource! I hope something like this can get implemented in Svelte like $resource one day.

Demo: Vercel
Repo: GitHub

J

Update 2/2/25

It is good practice to handle the abort controller, so I added a version for that as well.

export let resource = <T>(
    getter: () => RequestInfo | URL,
    initialValue?: T
) => {

    const _rune = $state<{ value: T | undefined }>({
        value: initialValue
    });

    const controller = new AbortController();
    const { signal } = controller;

    $effect(() => {
        const url = getter();
        fetch(url, { signal })
            .then((response) =>
                response.json()
            )
            .then((data) => {
                _rune.value = data;
            });
        return () => controller.abort();
    });

    return _rune;
};
ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025 ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025

This assumes you would call it:

const todo = resource<Todo>(() => 
    `https://jsonplaceholder.typicode.com/todos/${id}`
);

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025 ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025

There are many things you could do with this, maybe we will see something like this officially in Svelte.

J

Top comments (6)

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025
 
mark_stein_bef16e6723b997 profile image
Mark Stein •

This is awesome, thanks man

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025
 
webjose profile image
JosÃĐ Pablo Ramírez Vargas •

As a correction, the load function and SSR only exist in Sveltekit, so maybe the title should say Sveltekit. Remember that one can do Svelte in non-Sveltekit projects.

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025
 
jdgamble555 profile image
Jonathan Gamble •

Right, but this works in both Svelte and SvelteKit.

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025
 
webjose profile image
JosÃĐ Pablo Ramírez Vargas •

There is no load function unless you're in Sveltekit.

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025 Thread
 
jdgamble555 profile image
Jonathan Gamble •

Again, agreed, but you can use my resource function in both.

ðŸ”ī Hot News: jdgamble/async fetching in svelte - Kapook Update 2025
 
devmercy profile image
Mercy •

Works in both though