anarki
anarki

Reputation: 65

Can't fetch data from API in SvelteKit

I am trying to display data I request by fetch from API. Everything works well except fetch.

This is my component named Items.svelte:

<script>
  let items = [];

  async function load({ fetch }) {
    const url = "../r/api/items/all";
    let res = await fetch(url);

    if (res.ok) {
      return {
        props: {
          items: await res.json(),
        },
      };
    }
    return {
      status: res.status,
      error: new Error(),
    };
  }
</script>

{#each items as item}
  <header>
    <h2>{item.title}</h2>
    <p>{item.body}</p>
  </header>
{/each}

This is App.svelte:

<script>
  import Items from '$lib/Items.svelte';
</script>
    
<Items /> 

What am I doing wrong?

Upvotes: 5

Views: 8231

Answers (2)

VirgileD
VirgileD

Reputation: 757

In the docs (https://kit.svelte.dev/docs/loading) it says: "A component that defines a page or a layout can export a load function that runs before the component is created."

You can't use load from a component, only from a page or layout.

see also https://stackoverflow.com/a/67429568/1390405

Upvotes: 3

Akqira
Akqira

Reputation: 164

According to the documentation ---> https://kit.svelte.dev/docs/loading

You are missing the context="module" script section. It should be :

<script context="module">
    export async function load({ fetch }) {
        let res = await fetch('../r/api/items/all');

        if (res.ok) {
            return {
                props: {
                    items: await res.json()
                }
            };
        }
        return {
            status: res.status,
            error: new Error()
        };
    }
</script>


<script>
    export let items = []
</script>    

{#each items as item}
    <header>
        <h2>{item?.title}</h2>
        <p>{item?.body}</p>
    </header>
{/each}

Upvotes: 6

Related Questions