Error message: "Encountered an issue while accessing the 'id' property of a null value within the Vuex store module stored in

One issue I am facing is with my store module for current user. After logging into the app, I store user data in it. However, upon logging out and being redirected to the login page, I remove the current-user data from local storage.

Interestingly, following the logout process, a console error appears:

Cannot read property 'id' of null

This error stems from how I have configured values in my current user module:

const currentUser = {
    state: {
        id: JSON.parse(localStorage.getItem('current-user')).id || '',
        username: JSON.parse(localStorage.getItem('current-user')).username || '',
    },

The issue occurs because the code attempts to access the local storage object that no longer exists after deletion during the log out process. I'm seeking advice on the best approach to address this problem as I am relatively new to working with Vue and uncertain if my current implementation is appropriate.

Answer №1

give this a shot

let user = {
        info: {
            id:JSON.parse(localStorage.getItem('active-user')) && JSON.parse(localStorage.getItem('active-user')).id || '',
            name: JSON.parse(localStorage.getItem('active-user')).name || '',
        }

Answer №2

In my opinion, utilizing getters would offer a more effective solution, particularly when there is a need for some form of logic (even if it's as simple as checking for existence).

Here is an example:

const currentUser = {
  getters: {
    id() {
      const current = localStorage.getItem('current-user');
      if (current) {
        return JSON.parse(current).id;
      }
      return '';
    },
    username() {
      const current = localStorage.getItem('current-user');
      if (current) {
        return JSON.parse(current).username;
      }
      return '';
    }
  }
}

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

Struggling to Parse JSON Responses?

Utilizing AJAX/JQuery to communicate with a WCF service presents its own set of challenges. One common method is implementing .NET try/catch error-handling on the service-side to manage different scenarios, such as user timeout errors. Typically, the servi ...

Convert the shortDate format in AngularJS to display as 'M/d/yy' in a label or string

Can a short date format be converted to a string for displaying on a label? Specifically, I would like to use the format in my label. For instance, if I have <label>{{dateFormat}}</label>, then the variable dateFormat holds the value of the s ...

How can I apply various textures in three.js?

Hello there! I'm diving into the world of threejs and currently working on a block game similar to Minecraft. Instead of relying solely on objects, I've decided to build my program using planes (specifically the PlaneGeometry class). As I wrap ...

Exporting data from AngularJS to Excel is not functioning correctly in Internet Explorer. Additionally, the exported Excel file does not display properly in Firefox and

I have been attempting to Export a table from a jsp page to Excel using AngularJs. Is Angularjs not compatible with IE? I am also encountering this error SCRIPT5009: 'Node' is undefined In Chrome and Firefox, the Excel file only opens when save ...

Tips for preserving the content of a text field within the text field area

I have an HTML table with 3 fields, one of which is editable. The data for two columns is obtained as JSON - the fields are itemName and itemCode. The third column, Quantity, is manually created with a default value of 0. There is also a dropdown called ...

Error: The function `res.status` is unsupported

I've been working on a function to allow uploading images to imgur through my express API (nodejs), but I'm running into an issue when calling a function that returns a promise: TypeError: res.status is not a function at uploadpicture.then T ...

Is there a way to fetch a file using the fs readFile function in node.js without explicitly stating the file name?

I'm currently facing a challenge in retrieving a file from the file system to send it via API to the client. I am using Express.js for my backend and utilizing the 'fs' library. My goal is to achieve this without explicitly specifying the fi ...

Which should I opt for when defining a Model - Sequelize or DataType?

In my Node-Express app, I utilized Sequelize to manage a MySQL database. As I attempted to define a Teacher model by following the documentation, I came across two potential options. The initial option involved performing: var Teacher = sequelize.define(& ...

Issues with CSS background colors

I am in the process of streamlining my CSS code by consolidating repetitive elements and removing unnecessary lines (I am currently enrolled in a mobile apps course that emphasizes creating web-based hybrid applications using HTML5, CSS, and JavaScript, he ...

Vue.js problem with conditional rendering using v-if

I'm struggling to grasp the concept behind how v-if functions. My goal is to dynamically hide buttons in the navigation bar based on the user's authentication status and current page. Specifically, I want the "My Account" button to be displayed w ...

Ways to substitute EACH word in JQuery or JavaScript?

I've been attempting to substitute each word in a passage with another, but I haven't come across any method of achieving this. Here's an example: from this> Hello, my name is Robert. to this> Greetings Greetings Greetings Greetings ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

Error: Unable to find module 'app' in the injector. This issue is specific to Firefox browser

I've hit a roadblock with this issue. Despite reading extensively about it, I can't seem to solve it. The problem arises when I declare my <script> app.js before utilizing ng-app, leading to the following error: Failed to instantiate modul ...

Struggling to generate a fresh invoice in my project using React.js

I am fairly new to working with React and could really benefit from some assistance in understanding how to implement a new invoice feature within my current project. The Challenge: At present, I can easily create a new invoice as showcased in the images ...

What is the best way to extract text from a string that is enclosed by two particular words?

Using Ajax, I am extracting the complete HTML code from JSON. Once fetched, the string appears as follows : <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" cont ...

Repairing the 'Uncaught TypeError: Cannot read property 'split' of undefined' bug in a Prestashop Module

Help! I'm encountering an issue with a Prestashop module, and the developer is unresponsive. Can anyone shed light on why I am seeing this error in the console? Thank you so much in advance! admin.js:57 Uncaught TypeError: Cannot read property ' ...

Struggling to render ARGB unsigned long data onto an HTML canvas

I am currently working with an array of unsigned long ARGB data. This data represents a 16 x 16 image, which means it contains a total of 256 elements. However, I am facing difficulties in displaying this data. When I try to draw it using the code ctx.cre ...

Adjust the height of images to be consistent

I'm currently working on creating a grid layout with 4 images in a row using DaisyUI card component. However, I've run into an issue where there is white space at the bottom of some images due to varying image heights. Is there a solution that wo ...

I need help with making multiple XMLHttpRequests within a single JavaScript file. Can someone provide guidance on

https://i.sstatic.net/M0EJk.png Hey lovely people! I need some help. I'm trying to send two HTTP GET requests and log their responses in the console. However, I'm only seeing the response from the first request and the second one seems to be stuc ...

Identifying android devices with low resolution

Is there a method to determine if the current user is utilizing a low-resolution device (less than 320px) and then apply a distinct stylesheet specific to that user? ...