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

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...

How to Reload the Active Tab in Angular 5?

In my project, I have noticed that a listener in one of the tabs causes the entire tab to refresh, resulting in it displaying information from the first tab until I switch to another tab and then go back. 1) Is there a way to refresh only the current tab? ...

A data type that exclusively accepts values from an enumerated list without mandating the inclusion of every possible value within the enum

Here's a code snippet I'm working with: enum Foo { a, b, c } type Bar = { [key in keyof typeof Foo]: string; } const test: Bar = { a: 'a', b: 'b' }; I'm encountering an issue where the code is complaining ...

Visual Studio Code continues to compile code automatically without requiring me to save any changes

Question: VSC triggers compilation even without any file changes in Angular(6) project ng serve It's frustrating when Visual Studio Code starts compiling repeatedly, even when no changes have been made. How can I prevent this from happening? I&apos ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

Error suddenly appeared when trying to serve a previously functional project locally: Firebase function module not found

After not making any changes to my firebase-related files, I suddenly started encountering the following issue that I just can't seem to figure out: We were unable to load your functions code. (see above) - It appears your code is written in Types ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

Utilizing constants within if statements in JavaScript/TypeScript

When working with PHP, it is common practice to declare variables inside if statement parenthesis like so: if ($myvar = myfunction()) { // perform actions using $myvar } Is there an equivalent approach in JavaScript or TypeScript?: if (const myvar = myf ...

Displaying updated information in Angular

I recently developed a chat application using Angular that utilizes the stomp socket from @stomp/ng2-stompjs. To display all messages, I am leveraging *ngFor. <p *ngFor="let item of messages" style="padding: 5px; font-size: 18px"> <span style ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Issue with Jest: receiving error message "Module cannot be found" despite having the package installed

Recently, I went through a cleanup and update process for a private package to make it compatible with Vite. Initially, the package.json file had the following structure: { "name": "@myRegistry/my-package", "version": &qu ...

Tips for refreshing the service page in Ionic 2

One of my services is called "user-data", and its main function is to fetch "user data" when a request is received. I have a specific page that is responsible for displaying this "user data". Upon loading the page, it retrieves the data and displays it. ...

Creating a dynamic union return type in Typescript based on input parameters

Here is a function that I've been working on: function findFirstValid(...values: any) { for (let value of values) { if (!!value) { return value; } } return undefined; } This function aims to retrieve the first ...

Ways to specify the type signature for objects that incorporate a fresh method

My understanding is that in TypeScript, we use new() to structurally type a class constructor. But how do we type an object that includes a new method, for example: const k = { new() { return '123' } } ...

Adding strings in Typescript

I have the following code snippet: let whereClause = 'CurLocation =' + GS + ' and Datediff(DD,LastKYCVerified,GetDate()) >= 180 and CreditCard = ' + 'ACTIVE ' + &ap ...