MrCujo
MrCujo

Reputation: 1333

Sveltekit load function apparently not being called

I'm new to Svelte and Sveltekit and I'm working on a very basic app which has a page such as:

src/routes/categories/[slug]/+page.svelte

In another page I've got a link to the page previously mentioned. When a click on the link it successfully redirects me to [slug]/+page.svelte and I can see the URL well formed: http://localhost:5173/categories/test-6

Now, I'm trying to get the [slug] part of the URL when the page is loaded. I was going through the docs and read about the load function so I implemented:

<script context="module">

    /** @type {import('./$types').PageLoad} */
    export function load({params}) {
        console.log(params.slug);
        const slug = params.slug;
        return {
            slug
        };
    }
</script>

<script>
    let slug = undefined;
</script>


<h1>{slug}</h1>
wassap

but when I access the page I see only:

undefined
wassap

I don't even see the log statement I added to load.

What am I missing?

NOTEL I'm aware I could use perhaps onMount and $page and access the params in some other way, but I'd like to do it using load, seems so much cleaner to me.

Thanks

Upvotes: 2

Views: 4161

Answers (1)

Stephane Vanraes
Stephane Vanraes

Reputation: 16451

Your load function should no longer be in a context="module" block, but rather in a seperate file called +page.js:

export function load({params}) {
  console.log(params.slug);
  const slug = params.slug;
  return {
    slug
  };
}

the result of this is placed in an object data so in +page.svelte you would have now:

<script>
  export let data;
</script>

<h1>{data.slug}</h1>

Upvotes: 2

Related Questions