Obtain asynchronous state in VueJS without the need for intricate v-if conditions

I am working on an application that heavily relies on Vue-Router and Vuex for state management.

Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex.

The issue arises when subcomponents try to access this user information from the Store during their initial load. Sometimes, the user entry in the store is empty leading to a TypeError: $setup.user is null.

One common workaround is to add a v-if directive in front of each HTML element which can become quite cumbersome and inefficient in the long run.

Is there a better way to address this problem without littering the code with multiple v-if checks?

User.vue:

<template>
  <div>
    <div id="profile_content">
      <UserNavbar />
      <router-view :key="$route.fullPath" />
    </div>
  </div>
</template>

UserDashboard:

<template>
<div>
    <ProfileInformationCard>
      <span v-if="user">{{ user.name }}</span>
      <span v-if="user">{{ user.lastLogin }}</span>
    </ProfileInformationCard>
</div>
</template>

<script>
import _ from "lodash";
import { useStore } from "vuex" 
import { watch } from "vue" 

export default {
  setup(){
    const store = useStore()
    const user = store.state.user.currentUser

    watch(() => _.cloneDeep(store.state.user.currentUser), () => {
        user.value = store.state.user.currentUser;
      }
    );
  }
}
</script>

Answer №1

Instead of displaying the entire ProfileInformationCard, it's recommended to show a loading message or spinner like this:

<div>
    <ProfileInformationCard v-if="user">
      <span>{{ user.name }}</span>
      <span>{{ user.lastLogin }}</span>
    </ProfileInformationCard>
    <Loader v-else />
</div>

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

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Sequelize.js keeps the previous value for linked tables

My objective is to update the product status within the Product table. Each product has a statusId, which is either "1" or "2". The default value for statusId is always set to "1" for all products and should switch to "2" when the route is accessed once (a ...

Looking to transform a list into JSON format using JavaScript?

I have a collection that looks like this: <ol class="BasketballPlayers"> <li id="1">Player: LeBron, TotalPoints: 28753, MVP: true</li> <li id="2">Player: Steph, TotalPoints: 17670, MVP: true< ...

Tips on transferring a value from one JavaScript file to another JavaScript file

Currently, I am able to pass parameters from one JavaScript file to another using the jQuery method "$.getScript". For example, in the "secondJavaScript.js" file, I use a $.getScript call to invoke the function callMemoPage() from "firstJavaScript.js", p ...

Mini-navigation bar scrolling

I am trying to create a menu where I want to hide elements if the length of either class a or class b is larger than the entire container. I want to achieve a similar effect to what Facebook has. How can I make this happen? I have thought about one approac ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

What is the best method for updating the state of a dynamically created Switch component using React's setState()?

I have a dynamic creation of Switches based on a map like shown in the image: https://i.stack.imgur.com/jDLbS.png For example, using this code: const [enabled, setEnabled] = useState(false) return( ... {people.map((person) => ( ... ...

Initiate the python script on the client's end

Currently, I am in the process of initiating a Python script designed to parse a CSV file that has been uploaded by the user through the UI. On the client side, how can I effectively trigger the Python script (I have explored using AJAX HTTP requests)? Add ...

The question of when to utilize userEvent.click versus fireEvent in React Testing Library

I'm currently diving into the world of React-Testing-Library. One question that I have is regarding testing mouse interaction on an element. I find myself a bit confused about whether to use userEvent.click(element) or fireEvent.click(element). Can b ...

Receiving Request URL from XMLHttpRequest in PHP

I'm currently facing a dilemma as I work on a JavaScript script that is responsible for sending data from one of my forums to the server where a PHP script runs. The goal is to have the PHP script determine which JS output should be generated based on ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

``There seems to be an issue with the functionality of Passport.js' multiple login system

I'm encountering a strange issue with my login system. Everything seems to be working fine, including local login, Google login, and Facebook login. However, the problem arises when I attempt to register with Google after already registering with Face ...

Using $watch to monitor the existence of a variable within the AngularJS scope

I'm working on a directive that displays alerts, and I want to set up a timeout function to run whenever the 'show' variable changes. How can I achieve this? When I tried invoking the link function, all the variables - show, message, and ty ...

Using Sequelize and Express API for verification in the controller is an essential component of building

I'm currently working on building the API for my web app, utilizing Sequelize and Express. I have set up models with Sequelize and am in the process of developing controllers and endpoints. My main query is: Should I perform data validation checks be ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Resize a span's width using the width of another element using only CSS

Website Development <div class="container"> <div id="setter"> <span>some unique content here</span> </div> <div class="wrap"> <span> different text goes here, different text goes here, diffe ...

Incorrect positioning on canvas

Is there a way to adjust text alignment within a canvas? Currently, my text is centered. However, when I change the text size, the alignment gets thrown off. Here is the code snippet: <canvas id="puzzle" width="480" height="480"></canvas> ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

The npm lint command is throwing an "Observable `source is deprecated`" error

When I execute the command npm lint on my code, I receive a warning stating "source is deprecated: This is an internal implementation detail, do not use." The specific part of the code causing this issue is shown below: set stream(source: Observable<a ...

Rendering the Next.js Link tag on the page is displaying as [object Object]

Hey there! I'm currently working on creating breadcrumbs for a webpage and this is what the breadcrumb array looks like: const breadcrumbs = ['Home', "Men's Top", 'Winter Jacket'] Now, in JSX with Next.js, I am att ...