SvelteKIt - Access session - Function called outside component

Viewed 2195

I'm using SvelteKit with Typescript. In $lib folder, I have an .ts file.

I try to acces the user/session from '$app/stores' in the .ts file.

import { get } from 'svelte/store';    
import { session } from "$app/stores";

function getUser(){
  const {user} = get(session);
  console.log(user);
}

But when the function is called, i get the follow error message in the console:

Uncaught (in promise) Error: Function called outside component initialization

How can I slove this?

Many thanks!

1 Answers

I don't know at which point you call getUser, but it may be at other times than component initialization (else you wouldn't get this error), which means you need to structure things a little differently.

From the docs:

"...the stores are not free-floating objects: they must be accessed during component initialisation, like anything else that would be accessed with getContext. ...The stores themselves (...) need to be called synchronously on component or page initialisation when $-prefix isn't used. Use getStores to safely .subscribe asynchronously instead."

This means:

  1. Don't use session in this context, use getStores and assign to session yourself: const { session } = getStores()
  2. Make sure to call const { session } = getStores() during component initialization.

Example:

import { get } from 'svelte/store';    
import { getStores} from "$app/stores";

function getUser() { // <- call this at component initialization
  const { session } = getStores();
 
  return {
    current: () => get(session).user
  }
}
Related