Prop not loading on +page.svelte in svelte app

Viewed 65

Hi I am trying to fetch some data from an API (FastAPI running on same localhost on a different port)

here is the +page.js code

/** @type {import('./$types').PageLoad} */

export async function load({ fetch }) {
    const res = await fetch('http://127.0.0.1:8000');
    let message = await res.json()
    message = message.message
    if (res.ok) {
        console.log(message)
        return {
            message
        }
    }

    throw error("No data Received")
}

and here is +page.svelte:

<script>
    /** @type {import('./$types').PageData} */
    export let message;
</script>
<main>
    <div class="container">
        <h1>Hello World {message}</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae provident, labore qui modi minima voluptate perferendis est beatae non, molestias a, esse facilis deleniti error voluptatum iure harum magni debitis placeat ad! Amet numquam ratione iste?</p>
    </div>
</main>

<style>
    .container {
        width: 80%;
        margin: 0 auto;
        text-align: justify;
    }
    h1 {
        text-align: center;
    }
</style>

The console.log(message) in +page.js is logging the response but the {message} variable in +page.svelte component is undefined. what am i doing wrong.

PS: I am following the sveltekit docs from the official website.

1 Answers

All the props passed down from the various files (page.js, layout.js, ...) are now available in one big data prop.

<script>
 export let data;
 // assign it to a variable yourself
 $: message = data.message;
</script>

<!-- or use it directly from data -->
<h1>Hello {data.message}</h1>
Related