5

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?

2 Answers 2

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}
Sign up to request clarification or add additional context in comments.

7 Comments

Yes, it works, but only if I run this code directly in App.svelte. When I put it in the separate component it won't work. That is the question.
Do you have any error in DevTools console ?
Strange :) Could you upload it to public github repo. I will try it locally and try to help ;)
Also, could you show content of your '../r/api/items/all' file and where it's located. Maybe it's just a path issue as Items component is nested in $lib and App.svelte is not. So using ../ means one level up but from $lib it's maybe ../../ (two levels up)
This means that it's not reaching your own json. A tip is to use hooks.js (or ts) and implement function handle({ request, resolve }) to console.log the request and response. This help a lot to see exactly what's happening behind the scene
|
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.