Search code examples
javascripthtmlsveltekitthemoviedb-api

Using an API with Svelte


I'm having trouble fetching data from the moviedb using Svelte.

That's how I try to import the data.

<script context="module">
    export async function load({fetch}) {
        const res = await fetch(
            `https://api.themoviedb.org/3/movie/popular?api_key=<API_KEY>&language=en-US&page=1`
        );
        const data = await res.json();
        if(res.ok) {
            return {
                props: { popular: data.results }
            };
        }
    }
</script>

<script>
    export let popular;
    console.log(popular);
</script>

API output looks like this: enter image description here

The Commandline was giving me errors that popular is undefined, I have no clue why and I have tried different methods of fetching the data and assigning the variable, but none worked the way is should have.


Solution

  • If you are using an up to date version of SvelteKit, load works differently:

    • It should be defined in a route adjacent file, e.g. +page.js or +page.server.js (depending on where the code should run)
    • The returned object represents the props directly (without an additional props property)
    • The properties returned from the load function are injected into the page as a single property called data.

    See docs