Proper technique for handling asynchronous results in a Vue component

Where is the ideal place to wait for a promise result in the Vue component lifecycle? Here's a runnable example: https://codesandbox.io/s/focused-surf-migyw. I generate a Promise in the created() hook and await the result in the async mounted() hook. Is this the correct and most efficient way to utilize the Vue component lifecycle?

Note: I choose not to store the result as a mutation in the store since I may need to call this method multiple times. Instead, I return the Promise which retrieves user details from a REST endpoint.

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  actions: {
    FETCH_PROFILE: async context => {
      const profile = { name: "Leos" };
      return new Promise(function(resolve, reject) {
        window.setTimeout(function() {
          resolve(profile);
        }, 2000);
      });
    }
  }
});

component.vue

<template>
  <div class="hello">
    <p>Name = {{this.userProfile.name}}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data: () => ({
    userProfile: null,
    profilePromise: null
  }),
  created() {
    this.profilePromise = this.$store.dispatch("FETCH_PROFILE");
    console.log(`my profile: ${this.userProfile}`);
  },
  async mounted() {
    const response = await this.profilePromise;
    console.log(response);
    this.userProfile = response;
  }
};
</script>

Answer №1

If there isn't a strong reason to split this up between using both created and mounted, it would be more logical to handle everything in created. You don't need to worry about delaying the mounting process because async calls are non-blocking. It's recommended to utilize created over mounted, as the latter is typically used for manipulating the DOM or performing DOM-sensitive tasks.

async created() {
  const response = await this.$store.dispatch("FETCH_PROFILE");
  this.userProfile = response;
}

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

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

Having trouble making event listeners work with React useState in Next.js?

I'm currently working on a webpage where I want to have a fixed hamburger icon in the top-right corner that, when clicked, opens a navbar. The navbar should close if the user clicks outside of it, and the hamburger icon should reappear. Since Next.js ...

A router that has numerous parameters will not function properly with express.static

I successfully created an express router with the parameter 'router.get('/add')' and it is working perfectly. However, when I added 'router.get('/edit/:id')', the express.static feature stopped working, causing issue ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

Issue with CoffeeScript and three.js: scene not defined

I've been troubleshooting this issue for hours, but I can't seem to figure out the error... Here's the error message I'm getting: Cannot read property 'add' of undefined Below is my coffeescript code file (hopefully it&apos ...

Using REST api with Vue.js for authentication process

Currently, I am working on a project utilizing vue cli and adonis.js. The frontend will be exclusively developed with Vue.js, while the backend will solely offer REST API services. My plan is to incorporate jwt for authentication purposes. However, I am fa ...

What is the best way to switch a single class using jQuery without impacting other elements with the same class

I'm in the process of implementing a commenting system similar to Reddit on my website. Each comment is equipped with a small button in the top right corner that allows users to collapse the comment. To achieve the collapsing effect, I am utilizing j ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...

Tips for reorganizing the JSON data created by Artoo.js?

My file aims to scrape data from a single webpage, but I've hit a roadblock. I initially tried using artoo, request, and cheerio based on my research. Here's the code I have so far: request('http://www.ciclopi.eu/frmLeStazioni.aspx?ID=144&a ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

Automatically fill in an input field with jQuery by using the value from another input field

I am currently working on a loan calculator and am trying to find a way to automatically populate an interest rate field based on the loan amount entered. Here is an example scenario: For amounts ranging from 0 to 100,000, the interest rate is 4.50 For ...

What is preventing the random images from appearing on my browser?

Having some trouble loading random images on a page using basic JavaScript code. Following homework instructions, but the images are not showing up in the web browser. Any assistance would be greatly appreciated. Here is the code: <?xml version="1.0" ...

Tips for securely concealing an API key during website deployment on Netlify

Recently, I created a small website using Javascript just for fun and I'm looking to deploy it to Netlify. However, I've encountered an issue with the API key that the website uses. I'm struggling to figure out how to conceal this key. Curre ...

Error detected at /register/ Invalid Fernet key format - it should be 32 bytes in length and encoded in url-safe base

I'm currently working on encoding the payload data from a form I've made using React on the frontend. Here's the code snippet I am using: const handleSubmit = (e) => { e.preventDefault(); const encryptedPassword = CryptoJS.AES.en ...

Is your jQuery .on function failing to properly detect click events?

Seems like I'm missing something here. Why is the .on function not functioning as expected in this code snippet? <html> <head> </head> <body> <button type="button" class="close" data-test="test">TEST BUTTON< ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

Having issues initializing jQuery knob on a jQuery mobile webpage

I'm trying to implement the jquery knob plugin to showcase a circular rating system, but I'm encountering difficulties in getting it to display properly. Below is the code snippet I'm using - can someone please point out what's causing ...