Executing multiple axios.post calls in Vue to refresh the page

My code in App.Vue looks like this:

<script>
import axios from "axios";
import { baseApiUrl, userInfo } from "@/global";

export default {
  methods: {
    moveToLoginPage() {
      localStorage.removeItem(userInfo);
      this.$store.commit("setToken", null);
      this.$router.push({ path: "/login" });
    },
    async validateToken() {
      const json = localStorage.getItem(userInfo);
      const userData = JSON.parse(json);
      if (!userData) {
        this.moveToLoginPage();
      } else {
        const url = `${baseApiUrl}/auth/validateToken`;
        const resData = await axios.post(url, userData).then(resp => resp.data);
        if (!resData) {
          this.moveToLoginPage();
        }
      }
    }
  },
  created() {
    this.validateToken();
  }
};
</script>

After logging into the system, I navigate to another page and refresh it. Upon reload, Vue.app executes the code above to validate the token stored in localStorage. However, before receiving a response from the server in the validateToken() function, other HTTP.GET requests are triggered in the mounted() function of the refreshed page. Is there a way for the validateToken() function to finish executing before the mounted() function on the other page is called?

Answer №1

To implement async/await, follow this structure:

async init(){
    await this.checkAuth();
    }

By using this method, the initialization process will be paused until checkAuth retrieves a response.

Answer №2

If you have a router-view in your App.vue file, one approach is to use a flag or variable for your async data and then render the router-view only when that data is ready.

<template>
  <router-view v-if="data"></router-view>
</template>

By doing this, the inner children components will not be loaded until the asynchronous data has been fetched and made available.

This response essentially reiterates a previous comment I shared on a related question, provided here for the benefit of future readers.

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

Troubleshooting the Width Problem in Bootstrap 5 Dropdowns

I am currently working on a new project and encountering an issue with the width of a Bootstrap 5 dropdown. The problem lies in the discrepancy between the button width and the menu width. Although it may seem simple, I am having trouble resolving it as I ...

What are the steps to successfully submit my form once all the validation requirements have been met?

I successfully completed the validation process, but I am encountering an issue when trying to submit the form. An error message pops up indicating that there is an error related to a specific field (e.g., special characters being used). However, even when ...

Pressing on an HTML element using JavaScript via the Selenium driver does not trigger the action

I'm attempting to use Selenium with Python to click on an element using JavaScript. Here's a snippet of my code: driver.execute_script("els=document.getElementsByClassName('buttons');\ for (var i = 0; i < els.length; i++) { ...

"Secure access with Keycloak authentication in a .NET Core API and Vue.js Single Page Application

Currently, I am utilizing .NET Core for the backend REST API and Vue.js for the frontend. In my current setup, I have implemented authentication through a cookie. However, I am now looking to switch to authenticating via Keycloak. The goal is to have the ...

Issue with file operations in Ionic1 not functioning properly after scrolling in AngularJS

Working with Ionic v1 and AngularJS, I created a file-based handheld terminal app. However, I noticed that the scroll function stopped working after performing file operations. A workaround I found is that when I click or focus on a search box, the GET re ...

Error: The array's property is not defined

I am currently working on a visualization tool for sorting algorithms, but I keep encountering an error that says "Cannot read properties of undefined (reading 'map')" in line let bars = this.state.array.map((value, index) =>. You can find my ...

Encountering the error message "require is not defined" while running tests in AngularJS with Karma

I have implemented AngularJS with Browserify for my app development. To conduct testing, I have decided to utilize Karma. The configuration file I have set up is as follows: module.exports = function(config) { config.set({ basePath: '', ...

Could a jquery slick carousel be used to modify the body background of a webpage?

Is it possible to have one of the divs in a carousel change the background of the page, while the carousel is active on that specific div? if ($('.carousel').slick('slickGoTo', 1)){ //if slick is on slide index 1 //change to another pag ...

Bootstrap 5 dual carousel focus

I have implemented a combo carousel that serves as a timeline slider and displays 14 dates. Along with thumbnails, I am also using dates for navigation. To handle the large number of dates, I need to display them in separate rows, but only show one row at ...

Displaying only the records that are associated with the user using Laravel's relationships

After developing a system using Laravel and Vue.js, I have multiple users with access to the system. My goal is to ensure that each user can only view data related to their team. The system includes workers, teams, and jobs. When a worker is created, a cor ...

What is the best way to implement variable scope when using a callback function in AngularJS

I'm facing a major issue in my AngularJS application. I have a factory module with an getAll() function that retrieves JSON data from the server. In the controller module, I attempt to assign the value returned by the factory's getAll() function ...

Utilize DataTables with a custom search form for enhanced data filtering

I rely on DataTables for its advanced functionality in creating tables with paging capabilities. When submitting data through a standard jQuery Ajax request using my own form, the returned data is formatted and then passed to the DataTables function to en ...

Enclose every line within a span tag

I'm currently exploring ways to wrap each line of content in a span. For example, suppose I have an element structured like this: .body-copy { position: relative; width: 100%; height: auto } <div class="body-copy"> Lorem ipsum dolor s ...

Embed a React component seamlessly within HTML code

Hey there! I have a situation where I'm pulling valid HTML content from the database and I need to replace merge tags with working React components. The HTML is generated using a WYSIWYG editor. Let me give you an example: const link = <a onClick= ...

Exploring the documentation of node.js with doxygen

When it comes to my C projects, I make sure to document them using Doxygen. Recently, I delved into the world of NodeJs and attempted to document .js files with Doxygen, but unfortunately, no output was generated. Despite my efforts to search for answers ...

Display a Tooltip icon alongside a text field label with Vuetify components

Currently, I am utilizing Vuetify's component tooltip and experiencing difficulty implementing it right next to the label. Here is my current approach: <v-tooltip right> <v-icon slot="activator" dark color="primary">info</v-icon> ...

I am eager to create a Material-UI textfield using an array

My current task involves utilizing TextField based on an Array, but I am facing an issue with dynamically changing all the values. I understand that I can employ ternary conditions to accomplish this task effectively. const TextField = () => { r ...

Introducing the brand new feature: Video Mute Button!

Currently, I am working on implementing a mute button for a video on my webpage. The background of my page consists of a looping video with no other content, but the sound becomes quite bothersome after a while. While I have managed to find a button to pau ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...