The generated hook in vuejs is throwing an error stating that window/localstorage is not defined

My goal is to save an authenticated user to local storage and then load them into Vuex on the next page load.

created () {
    let user = window.localStorage.getItem('user')
    if(user) {
        this.setUser(JSON.parse(user))
    }
}

I initially believed that placing this logic in the created hook of my root component would be appropriate. However, I encountered the error 'window is not defined'.

After trying different approaches, I found that placing it in the mounted hook resolved the issue. Although, this did result in a brief display of the login page before loading the user information.

The question remains: where is the best location to put this logic?

Answer №1

To simplify your code, consider removing the window by eliminating the need to write

let user = localStorage.getItem('user')

If this solution is not enough for your requirements, you can utilize the vuex plugin available at https://github.com/robinvdvleuten/vuex-persistedstate. This plugin offers hassle-free functionality with zero configuration needed. You can specify a single value to be persisted by setting it as a path in the plugin's configuration settings.

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

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

The Complex World of JavaScript Variable Mutation

Currently, I have a loop in my code that checks the id of the last div on the page and uses AJAX to replace it with an updated div. However, if the loop runs again and the id remains the same, it just adds another duplicate of the updated div. My goal is ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

Update Json information within VueJsonCSV and VueJS component

I'm currently using the VueJsonCSV component to export data to a CSV file. The values being exported are retrieved from the Vuex Store. <template> <v-btn depressed> <download-csv :data="json_data"> Export Files </downl ...

Iterate through the collection to retrieve the value associated with a specific key

In the JSON response I have received, I am trying to extract the value of "fees" corresponding to "detailComponent" with the identifier "FULL_FEE". However, instead of retrieving the desired value, the loop seems to be fetching the last value associated wi ...

Choosing a single random key-value pair from a specific attribute within a JSON schema

Is there a way to generate a new JSON schema based on the existing one, but with only one key-value pair chosen randomly from the "properties" attribute? The new schema should retain the "title" and "type" attributes as well. { "title": "animals object" ...

Tips for dealing with event bubbling in React

Looking for a way to add an onBlur event to the left panel so that it closes when the user clicks on the right panel. I attempted using onMouseLeave but the closing animation isn't as smooth as desired. Additionally, I'd like for users to close t ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

Trouble with rendering inline images from markdown files in GatsbyJS

I've been trying to include inline images in my markdown file with the gatsby-remark-images plugin. However, I'm facing an issue where the image is not loading on my local host. I'm not sure if it's a syntax error or if I'm missing ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

Transformed 700 audio players compartmentalized within a nested tab interface. Optimal tab coding techniques include jquery, ajax

We are currently working on developing a nested tab interface that will include 700 audio players for MP3 files all on the same page within various tabs. However, only one audio player will be visible at a time and will only appear when the tab is clicked. ...

Utilizing pure JavaScript to dynamically fetch HTML and JavaScript content via AJAX, unfortunately, results in the JavaScript

I am trying to load an HTML file using AJAX and then execute a script. Here is the content of the HTML file I want to load: <div class="panel panel-body"> <h4>Personal Data</h4> <hr /> <span data-bind="editable: firs ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

Can a pledge be honored at a precise moment?

I have implemented transitions on my web page. When clicked, everything fades out to an opacity of 0 over a duration of 1 second. Then, a new page is swapped in and everything fades back in to an opacity of 1 over another 1-second duration. The issue aris ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...

Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this: { "soils": [{ "mukey": "658854", "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)", "sl_source": "Fl soil map", "cokey": "3035468", "soilName": "Eunola", " ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

Navigating within a React application - rendering JSX components based on URL parameters

As I work on developing a web-app with a chapter/lesson structure, I have been exploring ways to handle the organization of lessons without storing HTML or React code in my database. One idea I had was to save each lesson as a .jsx file within a folder str ...