admin管理员组

文章数量:1278917

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

This is my ponent 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?

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

This is my ponent 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?

Share Improve this question edited Feb 20, 2022 at 10:24 vhs 10.1k3 gold badges72 silver badges77 bronze badges asked Sep 6, 2021 at 13:32 anarkianarki 651 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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}

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

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

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

本文标签: javascriptCan39t fetch data from API in SvelteKitStack Overflow