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

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Personalized typeface for stencil.js element

I am currently working on a stencil component and I need to specify a font for it. Here is what I have so far: index.html <body> <sidebar-component webpagename="dashboard"></sidebar-component> </body> <style> * { m ...

Changing the information entered into a form within a subcomponent will result in all other fields being reset

I encountered an issue with my application that involves a form contained within a child component. The parent passes a prop (wizardData) to the child component. If the form is being used to input new data, the field values in the prop will be null; but if ...

Perform Action Only When Clicking "X" Button on JQuery Dialog

I have a dialog box with two buttons, "Yes" and "No", which trigger different functions when clicked. $('#divDialog').dialog({ modal:true, width:450, resizable: false, buttons: [{ text: 'Yes', ...

Step-by-step guide on starting Edge with Open package on Windows 10

I am utilizing the Open package to launch URLs across different browsers. Unfortunately, there is a lack of comprehensive documentation on how to specifically launch with different browsers on various operating systems. After some experimentation, I have ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

When a fresh tile is loaded in Mapbox, an event is triggered

As I work with the Mapbox GL JS API to manipulate maps, I find myself wondering if there is an event that can inform me whenever a new tile HTTP request is made. My code snippet looks like this: map.on("dataloading", e => { if(e.dataType ...

Calculating the v-model name dynamically within a v-for loop

I am currently working on a form that is dynamically generated with a v-for loop. Important Note: I am utilizing "@" to escape blade in this process. My Vue instance includes the following data: data: { form: { inputs: [{icon: "", name="", ...

Learn how to display two different videos in a single HTML5 video player

Seeking a solution to play two different videos in one video element, I have found that only the first source plays. Is jQuery the answer for this problem? HTML Code: <video autoplay loop id="bbgVid"> <source src="style/mpVideos/mpv1.mp4" type ...

Encountered an issue running "npm install" within the Vue3 composition API

Encountering an error while trying to install dependencies in a Vue3 project. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Vue.js components may not always display the data that has been fetched

Within a Laravel view, there is a component where the data in the select tag sometimes doesn't show up. It's quite strange as it randomly displays the data and other times it doesn't. There are no errors being logged in the console or the vi ...

What is the best way to fetch d3 data from a service?

I've been exploring a tutorial on creating charts with d3, which can be found at: When it comes to loading data for use in d3, I typically rely on the following code snippet: d3.tsv("data.tsv", type, function(error, data) { The file "data.tsv" is c ...

Discovering items within an array using Vue.js or JavaScript

I have an array of elements in Vue.js where I need to manipulate some data. For example, I have a select dropdown that displays company information with corresponding tags. These tags are at one sub level and are combined into one before being stored in th ...

Steps to import shared CSS using Styled-components

In my project using react, I've implemented styled-components for styling. One requirement is to have a shared loading background. Here is the code snippet of how I defined it: const loadingAnimation = keyframes` 0% { background-position: 95% 95%; } ...

Sending JSON data along with sendFile() in Node.js and Express done right

After setting up a Node.js server with Express and routing, I am faced with the challenge of passing JSON data onto a specific page ("/users/id") while using sendFile(). While I could make an AJAX request on page load to retrieve the data separately, I am ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

tips on assigning a unique ID to an item in a firebase database collection

My code is structured like this: const userCollectionRef = collection(db, 'users'); Then I add data using the following method : const addInfoToDataBase = async () => { checkLike(); await addDoc(userCollectionRef, { likePost: us ...

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...

I am attempting to implement an Express static middleware as demonstrated in this book, but I am having trouble understanding the intended purpose of the example

I'm currently studying a chapter in this book that talks about Express, specifically concerning the use of express.static to serve files. However, I'm encountering an issue where the code catches an error when no file is found. I've created ...