JAVASCRIPT
Handling Asynchronous Operations in Vue 3's setup Function
Perform data fetching or other asynchronous tasks before component rendering by using an `async setup()` function in Vue 3 Composition API.
// PostDetail.vue
<template>
<div>
<h2>Post Details</h2>
<div v-if="loading">Loading post...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<div v-else-if="post">
<h3>{{ post.title }}</h3>
<p>{{ post.body }}</p>
</div>
<div v-else>No post found.</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const post = ref(null);
const loading = ref(true);
const error = ref(null);
const postId = 1; // Example post ID
async function fetchPost() {
try {
loading.value = true;
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
post.value = data;
} catch (err) {
error.value = err;
} finally {
loading.value = false;
}
}
// Using onMounted for async call (alternative to async setup for direct data fetching)
onMounted(fetchPost);
// Alternatively, if the component itself can be async (e.g., used with <Suspense>):
/*
const { post, loading, error } = await (async () => {
const postData = ref(null);
const isLoading = ref(true);
const err = ref(null);
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
postData.value = data;
} catch (e) {
err.value = e;
} finally {
isLoading.value = false;
}
return { post: postData, loading: isLoading, error: err };
})();
*/
</script>
How it works: Vue 3's Composition API allows the `setup` function to be `async`, which is incredibly useful for fetching data or performing other asynchronous operations before the component is fully rendered. This example demonstrates fetching post details from an API. Although `onMounted` is used here for direct data fetching, an `async setup()` can also be utilized (as commented out) allowing parent components to wait for its resolution, especially when combined with Vue's `Suspense` component. This pattern simplifies component logic by centralizing data fetching with state management directly within the setup block, ensuring data is available when the component starts rendering.