Zeddrix Fabian
Zeddrix Fabian

Reputation: 2566

page.params is undefined in SvelteKit

I'm new in using SvelteKit. I read the docs (I'm doing my best to follow along and follow what's there to make my website work).

In my src > routes > posts > [postId].svelte:

<script>
    // http://localhost:3000/posts/[postId]

    import PostDetails from '../../components/pages/PostDetails.svelte';
</script>

<PostDetails />

In my src > components > pages > PostDetail.svelte:

<script>
   import { page } from '$app/stores';

   console.log({ page });
   console.log('page.params', page.params);
</script>

<h1>Post Title</h1>

I want to get the page.params.postId but it doesn't work. So I've decided to log the value of page and page.params on the console:

enter image description here

As stated in the docs, I was expecting to get { host, path, params, query } from this page object. But I got nothing but a subscribe function. What am I doing wrong? Please help.

Upvotes: 2

Views: 5319

Answers (1)

dummdidumm
dummdidumm

Reputation: 5426

page from $app/stores is a store, which means you need to subscribe to it to get the current value. That's because the value is not fixed but updates every time the page updates. To easily subscribe, to the store, prefix it with a $ sign:

<script>
   import { page } from '$app/stores';

   // manually (don't forget to unsubscribe in onDestroy to avoid memory leaks)
   page.subscribe(currentPage => console.log(currentPage));

   // easier
   console.log({ page: $page });
   console.log('page.params', $page.params);
</script>

<h1>Post Title</h1>

Docs on $app/stores: https://kit.svelte.dev/docs#modules-$app-stores
Docs on autosubscription with $: https://svelte.dev/docs#4_Prefix_stores_with_$_to_access_their_values

Upvotes: 5

Related Questions