What could be causing my conditional element to flicker during the loading of the route?

Situation: I am working on a webpage that dynamically displays different div elements based on the response received from an Axios request. If the response does not populate the data array called myExpense[], a div with the alert-warning class is shown. Otherwise, if the response does populate the array, a div with the alert-success class is displayed. Below is the code snippet:

<template>
  <div class="profilePage">
    <div class="container">

      <div class="row">

        <div class="col" v-if="Array.isArray(myExpense)
       && myExpense == 0"><!--Warning div-->
          <p class="alert alert-warning">You do not have a budget at the moment</p>
          <router-link to="/budgetform" tag="button" class="btn btn-primary mt-5">Create Budget</router-link>
        </div>

        <div v-else class="col-md-12 alert alert-success"><!--Success div-->
          <p class="yourBalance">
            Your monthly balance
            <br />
            <span>${{myExpense[0].earnings}}</span>
          </p>
          <router-link to="/mybudget" tag="button" class="btn btn-primary mt-5">My budget</router-link>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <a href="http://localhost:3000/auth/logout" class="btn btn-primary">Logout</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "userProfile",
  data() {
    return {
      myExpense: [],//This array to be populated by axios response
         };
  },
  methods: {},
  created() {
    axios
      .get("http://localhost:3000/budget", {
        headers: { "Content-Type": "application/json" },
        withCredentials: true
      })
      .then(res => {
        if (res.data.name == undefined) {
          this.$router.push("/");
        }
        this.profile = res.data;
        this.myExpense = res.data.budget;
      });
  }
};
</script>

Issue:

Upon rendering this page, there is a flicker of the wrong div before displaying the correct one based on the condition. Additionally, there are instances of white space being displayed.

Even after adding v-cloak, the problem persists.

Appreciate any assistance provided

Answer №1

After troubleshooting, I identified the issue. The get request was not fetching the data quickly enough for the page to render in time. To solve this, I utilized the beforeRouteEnter function to retrieve the data before the component is rendered.

Here's the updated code example:

beforeRouteEnter(to, from, next) {
    axios
      .get("http://localhost:3000/budget", {
        headers: { "Content-Type": "application/json" },
        withCredentials: true
      })
      .then(res => {
        next(vm => {
          vm.userName = res.data.name;
          vm.myExpenses = res.data.budget[0].expenses;
          vm.earnings = res.data.budget[0].earnings;
        });
      })
      .catch(err => {
        next(vm => {
          vm.err = err;
        });
      });
  }

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

Is it possible to include multiple API routes within a single file in NextJS's Pages directory?

Currently learning NextJS and delving into the API. Within the api folder, there is a default hello.js file containing an export default function that outputs a JSON response. If I decide to include another route, do I need to create a new file for it or ...

Obtaining font resources within a Vue application on a WordPress page template

When it comes to posting a question, I usually refrain from doing so unless I truly cannot find an answer. Unfortunately, that seems to be the case now. I am currently managing a project where a Vue app is being deployed within a page of a WordPress site. ...

Verify Departure on External Links within Wordpress

Let me set the stage for you: We're dealing with a bank website here. So, whenever a user wants to click on an external link (could be to a Facebook page or a partner website), we need to have a notification box pop up saying "You are about to lea ...

Swap out original source files in HTML with minified versions

I have successfully utilized a maven plugin to create a minified and compressed version of my CSS and JavaScript files. Now, I am looking to update the section in my main HTML page that currently loads all those individual files. Here is what it looks lik ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...

Retrieve a zip file using React and Node from a RESTful API

I have an application built with React and Node where I have a table that includes a download button. Clicking the download button triggers a request to my Node app, which in turn should call a REST API to download a zip file directly into the browser. In ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Tips for accessing the value of a specific key within an object that is nested in an array

I'm attempting to extract the name of the merchant from within this specific array: [ { "model": "inventory.merchant", "pk": 1, "fields": { "merchant_name": "Gadgets R Us", "joined": "2020-01-06T07:16:17.365Z" } }, ...

React is throwing an error: Uncaught SyntaxError stating that import declarations are only allowed at the top level of a module. This issue is coming

I encountered an issue where I received the error message: Uncaught SyntaxError: import declarations may only appear at top level of a module on index.js sometimes en index.css or bundle.js Despite this error, my App is not rendering and the div with id=& ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

Jquery Autocomplete has the ability to store and recall previous user selections

When the region is selected, autocomplete addresses should be displayed. Each time the region changes, the Jquery autocomplete function is called. While I am able to get the correct autocomplete addresses for the current region, I also receive address list ...

What is the best way to retrieve location data in a React application?

In my React project, I am trying to retrieve location information using the Geolocation API. To accomplish this task, I have included a button in the code below: import React, { Component } from 'react' class App extends Component { construc ...

Trigger the opening of a class or window upon pressing the button

Good evening, I'm attempting to create a functionality where pressing a specific button will open a window. However, I am unsure of how to achieve this using CSS classes. My initial thought was to add a new class in the CSS file and call it every ti ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

Pick Control - Utilize jQuery to display options that haven't been chosen before

Seeking assistance with a table view that includes a button for dynamically adding new rows. Each row contains a select control. Using Select2 for styling purposes. How can I ensure that when adding a new row, the select options only display those not prev ...

a guide on accessing key value elements within an array using Ionic 3

Just diving into the world of Ionic, I am currently working on a task to showcase products on the cart page that have been added to the cart. Upon fetching data from a REST API, I can see the response below in the console. "items": { "29.2.2.0.YTowOnt ...

Is there a way to retrieve the Boolean value from an ng-show attribute without having to re-evaluate the expression?

I'm currently working on a project that involves displaying and hiding a lot of content dynamically using ng-show. Some of the expressions being evaluated are quite lengthy, like this... <div ng-show="some.object.with.nested.values && ...

How can I acquire a duplicate of a Webgl texture?

I have a webgl texture and I have stored it in a JavaScript variable var texture1 = CreateTexture() function CreateTexture(){ var texture = gl.createTexture() // more WebGL texture creation code here return texture } I am looking to create a copy o ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

When you try to import from another file, the method is not defined

When I attempt to import a method from another file, I am encountering an issue where it returns undefined. The structure involves 3 files with one calling the next in sequence. File1: const { methodFromFile2 } = require('./file2'); methodFromFi ...