Home  >  Article  >  Web Front-end  >  Async Fetching in Svelte 5

Async Fetching in Svelte 5

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 10:27:02903browse

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;
};

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())
);

And show the value with:

{todo.value}

Similar Concepts in Other Frameworks

  • React Query
  • Vue watch
  • SolidJS createResource
  • Qwik useResource$
  • Angular 19 resource
  • ngxtension derivedAsync

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

The above is the detailed content of Async Fetching in Svelte 5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn