vue.jsasync-awaitaxios

How to fetch initial data in Vue 3 with async await before rendering?


I'm just started learning Vue 3. I want to load some initial data from an API to populate some fields before the App component is loaded. I checked the [documentation][1] and it says that top-level await can be used inside <script setup> but must be used in combination with Suspense which is currently experimental. The onMounted lifecycle method does not support asynchronous callbacks. After some research, I came up with this solution:

const isLoading = ref(true);
const user = reactive({
  firstName: '',
  lastName: '',
  email: ''
});

async function prefetch() {
  try {
    const res = await axios.get(vars.restUrl);
    user.firstName = res.data.firstName;
    user.lastName = res.data.lastName;
    user.email = res.data.email;
    isLoading.value = true;
  } catch (error) {
    // do something
  }
}


onMounted(() => {
  prefetch()
});

This works as expected but I was wondering if there is a better way. In Svelte, for instance, the onMount lifecycle hook can execute async code:

onMount(async () => {
    const res = await fetch(`/tutorial/api/album`);
    photos = await res.json();
})

Thanks [1]: https://vuejs.org/api/sfc-script-setup.html#top-level-await


Solution

  • I never had problems writing async in onMounted() hook in Vue 3 like this:

    onMounted(async () => {
       await prefetch()
    });