How can I use async/await in the Vue 3.0 setup() function using Typescript How can I use async/await in the Vue 3.0 setup() function using Typescript vue.js vue.js

How can I use async/await in the Vue 3.0 setup() function using Typescript


Try to use onMounted hook to manipulate asynchronous call :

 setup() {    const users = ref([]);    onMounted(async () => {      const res = await axios.get("https://jsonplaceholder.typicode.com/users");      users.value = res.data;      console.log(res);    });    return {      users,    };  },

LIVE DEMO


Another way of doing this:

 const users = ref([]);  (async () => {   const res = await axios.get("https://jsonplaceholder.typicode.com/users");   users.value = res.data;   console.log(res); })() return {   users, }

And you don't have to wait for it to mount, this is similar to using created() with the options API.

Note: Don't forget to always have a semicolon ";" before the function statement, otherwise, JavaScript would think that the previous statement was supposed to return a function, the following code, for example, would cause a bug "ref([]) is not a function":

const users = ref([]) // No semicolon here(async () => {

Another way of preventing this bug is to always have the semicolon on the same line of the function definition, the following code also works:

;(async () => {


An alternative is to use the promise chain, the benefit for doing so is that the code is run even before the beforeCreate lifecycle hook:

import { defineComponent, ref } from 'vue'import { getData } from './api.js'export default defineComponent({  setup() {    const users = ref([])    getData().then(({ data }) => (users.value = data))    return {      users,    }  },})