Tips for updating information within a vue-component

I am working on a Vue component where I retrieve data from localStorage. Here is how I handle it:

if (localStorage.getItem("user") !== null) {
  const obj_user = localStorage.getItem('user');
  var user = JSON.parse(obj_user);
} else {
  user = null;
}
return {
  user
}

Once the data is retrieved, I need to check and display it within the component. This is how I currently implement it:

  <li v-if="!user"><a href="/login">Login</a></li>
  <li v-if="user">
    <a href="#"><span>{{user.name}}</span></a>
  </li>

However, I have noticed that the data does not update immediately, but only after a page reload. For example, even after logging in and getting redirected to another page, the "Login" link still appears. What could be the issue here? Is there a different approach to checking and displaying data from localStorage within a component? Thank you for your help.

Answer №1

It seems like the issue at hand could be linked to the way your user variable is not being treated as reactive stateful data. While there is not enough code provided in your inquiry for a definitive answer, it appears that you are on the right path to understanding the correct approach in Vue.

In my opinion, a solution could resemble the following...

export default {
  data() {
    return {
      user: null,
    }
  },
  methods: {
    loadUser() {
      let user = null;
      if (localStorage.getItem("user")) {
        const obj_user = localStorage.getItem("user");
        user = JSON.parse(obj_user);
      }
      this.user = user;
    }
  },
  created() {
    this.loadUser();
  }
}

I store the user in the data section so that the template reacts to any changes in its value.

The loadUser method is kept separate so it can be called from various locations, such as a user login event, ensuring it is invoked during the component's created event.

In practice, I tend to place the user into a Vuex store and move the loadUser method to an action to enhance its global accessibility.

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

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Oops! Looks like the table you're trying to reference hasn't been defined yet

Whenever I attempt to create a table using the Google Visualization API, with PHP & MySQL in the background, I encounter this error message. The database connection is established without issues Generating JSON from the PHP array works correctly The JSON ...

Issue: Unhandled rejection TypeError: Unable to access properties of an undefined variable (retrieving 'data')

Currently, I am developing applications using a combination of spring boot for the backend and react for the frontend. My goal is to create a form on the client side that can be submitted to save data in the database. After filling out the form and attemp ...

Switching from Webpack-simple to Webpack in a Vue application: A step-by-step guide

I mistakenly created a vue application using webpack-simple, which I now realize is not suitable for deployment. Is there a way to switch to webpack without starting over with a new project? Thank you in advance. Edit: Below is the server.js code where I ...

Unexpected behavior with if statements in jQuery

Having recently started using jQuery, I am embarking on the creation of a survey. Each question within the survey resides in its own div and is unveiled upon clicking the "Next" button. Currently, all divs are hidden except for the current one. My approach ...

Tips for programmatically choosing images from a Google Photos collection?

Currently, I am attempting to use code in the console to automatically choose a photo from a Google Photos Album while browsing. I've tried this method so far: const photo = document.getElementsByClassName('p137Zd')[0].parentElement photo. ...

Exploring the creation of a dynamic graph with d3.js

I'm new to d3 and attempting to create a graph layout. var w = 1000; var h = 500; var dataset = { nodes: [{ name: 'Alice' }, { name: 'David' ...

When attempting to import the OrbitControls.js file, Three.js encounters an error and fails

I am completely new to javascript and unfamiliar with working with libraries. I am currently experimenting with basic three.js code, but unfortunately facing issues that I cannot seem to resolve. Following the documentation on Threejs.org, I have set up a ...

What is the best way to position and align an angle with the axis of a moving 3D figure?

My latest project involves a rotating planet, specifically Saturn with its iconic rings. To capture the best view of this celestial marvel, I configured the camera with precision: var camera = new THREE.PerspectiveCamera(45, width / height, 0.05, 1000); ...

Display or conceal a div depending on the selected radio button

I am attempting to display a hidden div based on the input of a radio button. If the "yes" option is checked, the hidden div should be shown. Conversely, if the "no" option is checked, the div should be hidden. I'm not sure why this code isn't w ...

Guide on inserting the elements <label>, <input>, and <span> into a <li> in a particular sequence

var btn = document.querySelector('.add'); var remove = document.querySelector('.draggable'); function dragStart(e) { this.style.opacity = '0.4'; dragSrcEl = this; ...

Vue is unable to access the properties of an object

After performing a find method within an array to search for the object, I am able to retrieve the object. However, I am facing issues accessing the properties within that object. The Nuxt error message states the following: Cannot read property 'v ...

Exploring discrepancies in jQuery AJAX responses between Chrome and Firefox

As someone who is not a front-end developer, I find myself working on a casual project that involves using AJAX to retrieve a piece of JSON data. $('#btn1').click(function() { $.ajax({ url: 'http://mywebsite.com/persons/mike&apo ...

"Is it possible to move the text on the canvas by dragging it to where you want it to be

Seeking help again after an unsuccessful attempt. How can I allow the user to add text to the canvas by dragging it to their desired location? For example, if they input text somewhere, it should appear on the canvas and then be draggable to any position ...

Is there internal access to the "access property" within the "data property" in JavaScript?

I have come to understand that there are two types of properties in objects: data properties and accessor properties. It is possible to access the "data property" without using an "accessor property," as shown below: const person = { name: 'Pecan&a ...

Is it possible to verify the authenticity of JSON data retrieved from

I'm currently working on validating JSON input from users and came across a challenge. I've found a way to check if the text a user enters is valid JSON using a simple function, like below: function IsJsonString(str) { try { JSON.par ...

"Troubleshoot: Inadequate performance of table search in node.js due

Embarking on a journey of learning here excites me. I have an insatiable appetite for new knowledge! Grateful in advance for any assistance! Presenting a concise Node.js JavaScript code snippet of 30 lines for a standard table search process. The "table" ...

Incorporate extra padding for raised text on canvas

I have a project in progress where I am working on implementing live text engraving on a bracelet using a canvas overlay. Here is the link to my code snippet: var first = true; startIt(); function startIt() { const canvasDiv = document.getElement ...

The parameters passed in an axios get request are not carried over to a create request

Exploring the capabilities of the YouTube API with ReactJS While working with the YouTube API, I came across the create method in axios. However, I faced an issue where the params were getting overwritten. What am I missing here? I have a file named yout ...

Incorporating base Tailwind CSS colors with the daisyUI theme: A simple guide

For my NextJS project, I'm utilizing Tailwind CSS in conjunction with daisyUI. In my configuration file tailwind.config.js, I have it set up as follows: /** @type {import('tailwindcss').Config} */ /* eslint-env node */ module.exports = { ...