Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda