I have a navigation bar that loads user data, all this happens after the user successfully logs into the application. The problem is, after loading the navbar, localStorage has to be set slightly. If I wrap it in setTimeout() everything works fine, but I'd rather my variables be reactive in nature since they 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>
I've tried using observers, and using setup() and data(), but nothing seems to work properly. As I mentioned, setTimeout() does work, but I'd rather avoid triggering the timeout manually and let vue handle things the way it wants.
This is a simple example, I can't set up the dummy code side because it doesn't have a localStorage itemset.
For some additional context, after the user logs in, I use async() to call the API to get the account information and store the account data in localStorage. I'm guessing that the router is trying to load the navigation bar area, which is why the localStorage project is not available when the component is installed.
I don't know the vue3 word to use, but ideally I'd like to have some kind of async/await call to localStorage since ref() doesn't seem to be working the way I thought it would. It's like ref() doesn't see localStorage getting updated.
The synchronization of localStorage is the main problem.
Use installed lifecycle hooks. And initialize user information there