Creating a singleton object to hold data across different pages

Viewed 150

I am trying to hold some data about my user who logged in. When I try to reach the data of my singleton that was created in a previous page, the singleton is reinitialized and all data lost

This is my singleton code: in profile.js

const databaseURL  = "************************";    

    class ProfileOBJ{
       async fetchProfile(id){
             var profile = await (await fetch(databaseURL +'/user/'+id)).json();
                console.log("Json response");
                console.log(profile)
             this.parseProfile(profile)
                  
       }
    
       async login(id){
           if(this.loggedIn){
                return;
           }
           await this.fetchProfile(id)
           this.loggedIn = true;
       }
    
    
       parseProfile(profile){
            this.moderator = profile.moderator;
            this.questionData = profile.questionData;
            this.progressionData = profile.progressionData;
            this.id = profile._id;
            this.institution = profile.institution;
       }
    
    
  
        constructor() {
            
        }
    }
    
    
    
    window.Profile = class{
    
        static instance;
    
        constructor() {
            if (this.instance == undefined) {
                this.instance = new ProfileOBJ();
            }
        }
    
        getInstance() {
            return this.instance;
        }
    }

I import this file to my HTML file like:

<script src="profile.js"></script>

and I use it like:

let user = (new Profile()).getInstance(); 
console.log(user);

When I route to other pages like:

   window.location.href = "./secondPage.html";

class gets reinitialized so all the data is lost

I wonder if there is any method to hold such information accessible from different HTML pages

1 Answers
Related