I have a Vue3 app using the composition api and want to fetch data asynchronously inside the setup
function.
Approaches that worked for me:
Working with Promises
<template>
<div>{{ result }}</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const result = ref();
fetch("https://api.publicapis.org/entries")
.then((response: Response) => response.json())
.then((jsonResponse: any) => {
result.value = jsonResponse;
});
return { result };
},
});
</script>
Working with the onMounted
hook
<template>
<div>
{{ result }}
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
export default defineComponent({
setup() {
const result = ref();
onMounted(async () => {
const response = await fetch("https://api.publicapis.org/entries");
result.value = await response.json();
});
return { result };
},
});
</script>
But I wasn't able to use async/await directly like so
<template>
<Suspense>
<template #default>
{{ result }}
</template>
<template #fallback> Loading... </template>
</Suspense>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
async setup() {
const result = ref();
const response = await fetch("https://api.publicapis.org/entries");
result.value = await response.json();
return { result };
},
});
</script>
Based on this question
@vue-composition / How can I use asynchronous methods in setup()
and this linked article
https://vueschool.io/articles/vuejs-tutorials/suspense-new-feature-in-vue-3/
it should work.
The posted component is just the default Home.vue component rendered by the Vue router. So inside App.vue I'm using the tag <router-view />
and load the app with the home route.
How can I mark setup
as async
?