Search code examples
sveltesveltekitsvelte-store

How to get data from a Svelte store to +page.js?


In the +page.svelte I import my store import { authStore } from '../stores/authStore'; and then I can access the user ID from the store like this:

let uid;
authStore.subscribe((curr) => {
    uid = curr?.currentUser?.uid;
});

But how can I access it in the +page.js? console.log('uid: ', uid); will give me uid: undefined

OK, I can store it in the cookies but that is not that secure.


Solution

  • It's a little unclear what you're actually trying to do, but variables aren't shared between page.svelte and page.js by default, so of course uid is going to be undefined in page.js. You could just subscribe to it in page.js exactly like you were doing in page.svelte:

    authStore.subscribe((curr) => {
        uid = curr?.currentUser?.uid;
    });
    

    However, the typical reason to even have a page.js file is to populate the data needed for page.svelte by means of a load function which gets called first. So you probably want to do something more along the lines of:

    import { get } from 'svelte/store';
    import authStore from './stores'
    
    export const load = async () => {
        return get(authStore); // gets the current value
    }
    

    And then in your page.svelte you can import that data like so:

    <script>
        export let data;
        console.log(data); // contains whatever load() returned, so the value of authStore
    </script>
    

    Again, there's not a lot of detail in your question that would explain why you want to get the value of authStore in the .js rather than in the .svelte file, so it's hard to say if that even makes sense.