Storing data in the browser's LocalStorage after a Vue3 component has

Whenever a user successfully logs into the application, a nav bar is supposed to load user data. However, there seems to be a timing issue with localStorage being set slightly after the nav bar is loaded. Using a setTimeout() function resolves the issue, but I would prefer a more reactive solution as the variables can change based on user activity.

Toolbar.vue

<template>
  <!--begin::Toolbar wrapper-->
  <div class="d-flex align-items-stretch flex-shrink-0">
    <h2>check for value</h2>
    <div v-if="activeAccountId">{{activeAccountId}}</div>
  </div>
  <!--end::Toolbar wrapper-->
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "topbar",
  data() {
    let activeAccountId = ref(JSON.parse(localStorage.getItem('activeAccountId') || '{}')).value;

    return {
      activeAccountId
    }
  }
});
</script>

Despite trying watchers and using setup() instead of data(), the issue persists. While setTimeout() works, I am hesitant to manually trigger a timeout and would prefer Vue to handle this asynchronously. Creating a dummy code example is not possible as the localStorage item needs to be set.

After the user logs in, an async() call is made to the API to retrieve account information and store it in localStorage. It seems that the localStorage items are not available when the component mounts because the router is trying to load the navbar area simultaneously.

While I am unclear on the specific Vue 3 terminologies to use, I am looking for an async/await solution to retrieve data from localStorage as the ref() method does not seem to update accordingly. The synchronous nature of localStorage seems to be the root cause of the issue.

Answer №1

Vue triggers the mounted() lifecycle hook once the component is inserted into the DOM. It is recommended to place your initial code inside the mounted method and consider modifying your code to resemble the following:

export default defineComponent({
  name: "topbar",
  data() {
    return {
     activeAccountId:""
    }
  },
  mounted(){
    this.activeAccountId = JSON.parse(localStorage.getItem('activeAccountId')|| '{}');
  }
});

Answer №2

When working with user information, it's recommended to utilize the mounted lifecycle hook to ensure proper initialization.

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

How to activate another component's method using Vue.js

my files are structured as follows: ./components/UserCreate.vue ./components/UserList.vue ./main.js inside main.js, my Vue instance is defined as: new Vue({ el: '#user-operations', components: { CreateUser, UserList } }); Th ...

Troubles arise when hovering over and connecting endpoints in jsPlumb

I'm currently facing two challenges with my project. Follow this link for more details. 1) The hover effect is working perfectly on the endpoints, but I can't seem to change the colors of my connector when hovering over it. Any suggestions? (Ref ...

Ways to set control values with AngularJS

After retrieving a single record from the database for my detail view, I need to assign data to controls. Take a look at my code snippet below: var app = angular.module("MyProductApp", []); app.controller("ProductsController", function ($scope, ...

Ways to acquire dynamic content without relying on Remark/Grey Matter

In my stack of technologies, I am using nextJS with react and typescript. While I have successfully set dynamic routes for my blog posts, I am now facing a challenge in creating pages that do not rely on markdown. Despite searching extensively for code exa ...

"Uncaught Error: Unable to retrieve null properties" encountered while utilizing regex match in cheerio web scraping

Extracting text from brackets in HTML using regex: <dl class="ooa-1o0axny ev7e6t84"> <dd class="ooa-16w655c ev7e6t83"> <p class="ooa-gmxnzj">Cekcyn (Kujawsko-pomorskie)</p> </dd> <dd class="ooa-16w655c ev7e6t ...

Switch all occurrences of https URLs with <a> using the stencil technology

I am encountering an issue with replacing the answer retrieved from an API and formatting it correctly answerFromAPI = "textword textword textword textword textword.\n\nFeel free to ask me questions from this site:\nhttps://google.com &bso ...

Grouping object properties in a new array using Java Script

I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects. For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a n ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

Are MEAN stacks and boilerplates suitable for custom applications requiring specialized functionality?

After spending a significant amount of time learning and coding, I have encountered a common issue. You can find the link to the discussion below. Instead of reinventing the wheel, should I utilize existing boilerplates that combine Express, Angular, conn ...

What are the steps to build a dynamic webpage in a Django project?

For my Django app, I have successfully created static pages without any ajax requests. However, I now want to add a dynamic subpage that can change its content without refreshing or reloading the entire page. Let me explain what I'm trying to achieve ...

Get a document from a Vue app using the Cordova InAppBrowser plugin

I have a Spring Boot + Vue.js application server running on the network. Additionally, I have a Cordova InAppBrowser Android app that displays the frontend. I need the ability to access the application from both a real browser on a computer and from the C ...

Retrieving the selected values of TimePicker (hour and minute)

Posting my question here as the vue.js forum appears inactive and I'm unable to receive a confirmation email via Slack. I've recently begun coding with .vue and have come across an inquiry. Upon selecting a time using the timepicker, I would li ...

What is the best way to trigger a refresh callback on Angular datatable pagination after updating the data

I've successfully set up my angular datatable configuration. Here's what it looks like: vm.dtOptions = DTOptionsBuilder.newOptions(). withPaginationType('full_numbers'). //withOption('ajax', { ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Unique version: "Vuejs encountering strange MySQL date formatting"

MySQL stores time in this format: 2022-04-25 11:03:20 However, when displayed on the client with Vue.js, it appears like this: 2022-04-25T09:03:20.000Z Is there a way to display it exactly as it is stored in the database? ...

Calculating the total of values in a vuejs and laravel table

I need assistance with calculating the total amount in a table that includes quantity, unit price, and their totals using Vue.js and Laravel. I am looking to loop through the database elements and only display certain elements via v-if. Any guidance on how ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...