Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts">
import { createComponent } from "@vue/composition-api";

import { SplashPage } from "../../lib/vue-viewmodels";

export default createComponent({
  async setup(props, context) {
    await SplashPage.init(2000, context.root.$router, "plan", "login");
  }
});
</script>

WARNING: The "setup" function should return an "Object" or a "Function" but it is currently returning a "Promise"

Answer №1

It is essential for the setup function to be synchronous, but there is a way to make it asynchronous using Suspense.

Alternative to using async setup (not recommended)

You can utilize the onMounted hook with an async callback like so:

import { onMounted } from "@vue/composition-api";

// …
export default createComponent({
  setup(props, context) {
    onMounted(async () => {
      await SplashPage.init(2000, context.root.$router, "plan", "login");
    )};
  }
});

Alternatively, you can call an asynchronous function without awaiting it:

SplashPage.init(2000, context.root.$router, "plan", "login")
  .catch(console.log);

In both scenarios, remember that the component will render before the asynchronous function executes. To avoid displaying something dependent on it, consider using v-if in your template.

Answer №2

I've come up with a different solution that works for my specific case. Maybe it could be useful to others too. It's somewhat similar to the lifestyle hook approach, but without the need for it. Additionally, it doesn't require the use of the <Suspense> tag, which I found to be unnecessary in my scenario.

The concept is to initially return a default value (in this instance, an empty array, though it could be a "Loading..." splash page). Then, once the async operation has completed, update the reactive property (in this case, the menuItems array, but it could also be the actual content of the splash page or HTML).

I understand that this approach may not be suitable for all situations, but it's another method that proved effective for me.

Here is a simplified version of the code:

setup () {
  const menuItems = ref([])

  const buildMenuItems = async () => {
     // example: fetch items from server and format them into an array...
  }
  
  /* setTimeout(async () => {
    menuItems.value = await buildMenuItems()
  }, 0) */ 

  // or..
  ;(async () => {
    menuItems.value = await buildMenuItems()
  })()  

  return {
    menuItems
  } 
}

I tested this by intentionally delaying buildMenuItems() by 2 seconds, and everything functioned correctly.

UPDATE: I also came across other techniques (even applicable to non-TypeScript setups): How can I use async/await in the Vue 3.0 setup() function using Typescript

Cheers, Murray

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

Store the active tab in AngularJS with Bootstrap to easily remember and display

After creating a basic AngularJS application with the Bootstrap directive, I noticed that some of my pages have tabs. The issue arises when I am on a tab other than the first one and click a link to navigate to another view. Upon returning (using either th ...

Troubleshooting Error: Module build failure in node-sass and sass-loader. TypeError encountered: 'this.getResolve' is not a function within the

I'm currently following a tutorial that instructs me to install both node-sass and sass-loader. However, upon installation, I encountered the following error: ERROR Failed to compile with 1 errors ...

`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation: Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing bein ...

Display/Hide Location Pins on the Map

Looking for some assistance, please. I'm currently working on a script to toggle the visibility of locations on a map. The main code I've been using can be found here, and my own code is displayed below: !DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

"Implementing form validation and AJAX submission for seamless user interaction

I am seeking a solution to validate my form using ajax and then insert it into the database also utilizing ajax. Although, with the current code, validation messages are displayed, it still performs the insertion. The issue I am encountering seems to be ...

Utilizing AJAX and PHP to refresh information in the database

For my project, I need to change the data in my database's tinyint column to 1 if a checkbox is selected and 0 if it is deselected. This is the Javascript/Ajax code I have written: <script> function updateDatabaseWithCheckboxValue(chk,address) ...

Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab. The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor fo ...

Issue with displaying Font-awesome icons within a Vue.js v-for loop - icons are showing up as text instead of rendering properly

When looping an element four times with a v-for in Vue, all content renders correctly except for Font Awesome icons which show up as HTML text. Below is the code snippet causing the issue: HTML: <div class="second-section-paragraph-1" v-for=& ...

Select the default option and what occurs in the event of an HTTP connection

I am currently facing an issue with two aspects. Firstly, I am struggling to set a default option in my Select element. Despite using ng-model, it only displays a blank option at the moment: <select class="form-control" ng-model="pageSize"> ...

Upon refreshing the browser page, AngularJS fails to redirect to the default page as expected

In my AngularJS route configuration, I have set up the following paths: moduleA.config(function($routeProvider){ $routeProvider. when('/A',{templateUrl:'A.jsp'}). when('/B',{templateUrl:'B.jsp'}). wh ...

Improving the retrieval of API data using personalized React hooks when searching by modifying keywords

I'm just starting out with React Hooks and recently wrote a small code snippet that displays a list of courses to users. This code includes two main components, CourseList and Course, as well as a custom hook called useCourseList. Here's the code ...

What method can I use to adjust the font style when it overlays an image?

Sorry if this is a bit unclear, but I'm trying to figure out how to change only a section of my font when it overlaps with an image while scrolling. If you visit this example website, you'll see what I'm referring to: For a visual represen ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

Retrieve the Javascript variable and assign it to a PHP variable

When attempting to assign a JavaScript variable to a PHP variable and output the value in an alert, I am encountering an error. The output is shown as "; alert(simple); var p1sds = "My Custom String"; <?php $dsfd = "<script>document.writeln(p ...

Mastering the Art of Modifying HTML with Node.js

Is it possible to manipulate HTML using Node.js? 1. First, I need to retrieve data from a database. 2. Then, I need to modify or add HTML code within Node. In essence, the goal is to fetch data and integrate it into an HTML file. The JavaScript snippet ...

Request to api.upcitemdb.com endpoint encountering CORS issue

This code may seem simple, but for some reason, it's not working as expected. What I'm trying to achieve is to call the GET API at: I want to make this API call using either JavaScript or jQuery. I've attempted various approaches, but none ...

"Exploring the process of retrieving URL parameters within an activated link using Angular 7 and executing a REST API call from a service

My aim is to retrieve data by utilizing the id field through Get parameters. Below is the URL code in my HTML that redirects to a specific page without triggering the service to fetch the REST API. <a [routerLink]="['/usedCars/detail', list ...

Encountering unidentified data leading to the error message "Query data must be defined"

Currently, I'm utilizing Next.js to develop a project for my portfolio. In order to manage the API, I decided to implement both Tanstack query and Axios. The issue arises when attempting to retrieve the data as an error surfaces. Oddly enough, while ...

What is the method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance. Upon rec ...

The content has been successfully loaded using ajax, but it is not displaying

I've been experimenting with djax and have noticed that when I click on an anchor tag, the URL changes as expected. However, even though the page source reflects this change, the contents of the page itself remain unchanged. Any thoughts on why this m ...