Error in SvelteKIt: Unable to access session due to a function being called outside of

Using Typescript in SvelteKit, I have an .ts file located in the $lib folder.

Attempting to access the user/session from '$app/stores' within the .ts file results in the following code snippet:

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

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

However, upon calling the function, an error message is displayed in the console:

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

Any suggestions on how to resolve this issue would be greatly appreciated!

Thank you in advance!

Answer №1

If you're wondering when to call the getUser function, it's important to note that it may need to be called at times other than during component initialization in order to avoid errors. This suggests that you should consider structuring your code differently.

According to the documentation:

"...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. Avoid using session directly, and instead use getStores to retrieve it and assign it to session yourself: const { session } = getStores()
  2. Ensure that you call const { session } = getStores() during component initialization.

Here's an example of how this could be implemented:

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
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

Tips for sending an array containing objects with an ID using Angular

Can you give me your thoughts on how to post an array with some object? This is the code I am working with: const selectedJobs = this.ms.selectedItems; if (!selectedJobs) { return; } const selectedJobsId = selectedJobs.map((jobsId) => ...

In TypeScript, the error "Property does not exist on type 'any[]'" indicates that a specific property is not recognized on

Working on my project using Textscript in Next Js has been mostly smooth sailing, but I keep encountering warnings in my script that say 'Property does not exist on type any[ ]'. The red line under the name, image, and price properties is a sourc ...

Storing Global Types in Angular: A Better Approach

Imagine I possess certain universally applicable enums, interfaces, or extensive classes. For example: export interface LogMessage { code: number; message: string; } Where would be the optimal location to store them? What is considered the best pr ...

Issue encountered when trying to bring in a component from a different module

I am attempting to import the 'OpenDialogContentComponent' component from Module A into Module B, however I am encountering this error: 'Cannot determine the module for class OpenDialogContentComponent in C:/Users/jitdagar/Desktop/TDP/pwt-u ...

Create a function that recursively maps data across multiple levels

Currently, I have a data mapping function that can take JSON data with up to four levels and transform it into a different format. The input JSON format looks like this: [{ "InventoryLevel2Id": "1234", "InventoryLevel2Information": "Test Data", ...

Is it true that after setting the state in the main app with React/Recoil, it cannot be reset within a component?

Upon setting the state from the loadable within the App.js file: import React from 'react'; import { useRecoilState, useSetRecoilState, useRecoilValueLoadable } from 'recoil'; import './App.css'; import { Point } from './ ...

Encountering an "emit" error while working with PouchDB in Angular 2

Within my Ionic2 application, I have created a provider to inject PouchDB design documents. However, I encountered this TypeScript error: Typescript Error Cannot find name 'emit'. src/providers/design-docs.ts if (user.location) { emit(user ...

Validation parameters provided during the Palantir workshop

At our Palantir workshop, we utilize a form to input values that are then added to an Ontology object. Recently, I've been tasked with validating the combination of userId, startdate, and states from the form inputs to check if they already exist or n ...

Showing a div based on the selection of multiple options from a multiselect

I am having trouble implementing a show/hide functionality based on a multiselect dropdown in my Angular and Typescript project. Specifically, I want to display a div with another dropdown menu when the user selects a certain option from the multiselect ...

Difficulty fetching data on the frontend with Typescript, React, Vite, and Express

I'm currently working on an app utilizing Express in the backend and React in the frontend with typescript. This is also my first time using Vite to build the frontend. While my APIs are functioning correctly, I am facing difficulties fetching data on ...

The most effective approach to creating linked observable subscriptions

How can we refactor this code reactively using RxJS for better performance? let profileInformation; updateProfile() { let token; let profileId = 1; this.userService.getAccessToken() .pipe( tap((res) => { //as I need it multipl ...

Unexpected error in React TypeScript: '=' symbol missing. Code error TS1005

Encountering an issue: '=' expected. TS1005 5 | * LICENSE file in the root directory of this source tree. 6 | */ > 7 | import type { NewPlugin, Optionsz, OptionsReceived } from './types'; | ^ ...

The 'AppsList' generic type needs to have one type argument specified.ts(2314)

Consider the following interface that represents an array of objects. export interface App { entry: object; content: { label: string; visible: boolean; }; name: string; length: number; } export type AppsList<Response ...

Using ViewChild in Angular 4 to set focus on dynamically generated textboxes

Below is an example of a dynamically generated textbox: <tr *ngFor="let item of data; let in=index"> <td> <input #unitNumber type="text" name="workPerformed-workcode-{{in}}" [(ngModel)] = "item.unitnumber" > ...

Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state. My goal is to specifically fetch the 'numberOf ...

Converting Mat-Raised-Button into an HTML link for PDF in Angular 6 using Material Design Library

Greetings, I have a couple of interrelated inquiries: Upon clicking the code snippet below, why does <a mat-raised-button href="../pdfs/test.pdf"></a> change the URL (refer to image 4) instead of opening test.pdf in a new window? If I have a ...

The process of transferring information from a JSON API to TypeScript models

When working with my JSON API in my services, I need to pass the data to my models. What is the most efficient way to accomplish this task? Currently, I am following this process: import { Attachment } from '.'; export class Contact { id: nu ...

Properly capturing an item within a TypeScript catch statement

I am dealing with a scenario where my function might throw an object as an error in TypeScript. The challenge is that the object being thrown is not of type Error. How can I effectively handle this situation? For example: function throwsSomeError() { th ...

Received 2 arguments instead of the expected 1 in the custom validator causing an error (ts 2554)

After implementing the following validator, I encountered an error message. The error states: "Expected 1 argument, but got 2 (ts 2554)." Although many sources mention overloading as a common issue, there is no overload present in this case. export const ...