Search code examples
fetchloadsveltesveltekitsvelte-5

Svelte 5 how to fetch data from an API?


I am not sure how to fetch data in SvelteKit 5. In the below data is a Proxy object

<script>

export async function load({ fetch }) {
    const res = await fetch('https://renovatorsparadisewebsite.kinsta.cloud/wp-json/rp2024/v1/top-menu');
    const data = await res.json();

    return {
      props: { data }
    };
  }

  const { data } = $props();

  console.log(data);

</script>

enter image description here

I tried changing the variable name data


Solution

  • Svelte 5 uses proxies for state (including props) to enable its reactivity system.

    The proxy fires a signal on property access so effects like the rendering of the component will update when the property is changed.

    You can access the proxy just like the source object. The proxy will only affect things like serialization and equality comparisons (for both there are runes to deal with that: $state.snapshot & $state.is).

    To unwrap the proxy, use $inspect instead of console.log or get a $state.snapshot.

    Nothing about data loading itself is changed here.