Vue 3 Data Fetching with Suspense
Fetch async data in Vue 3 using Suspense components, async setup, and error boundaries. Provides loading fallbacks, error recovery, and TypeScript typing.
Code
import { defineComponent, ref, onErrorCaptured } from 'vue';
interface Post {
id: number;
title: string;
body: string;
}
export default defineComponent({
async setup() {
const posts = ref<Post[]>([]);
const res = await fetch('https://api.example.com/posts');
posts.value = await res.json();
return { posts };
},
template: '<div v-for="p in posts" :key="p.id">{{ p.title }}</div>',
});Under the hood
Every asynchronous step is awaited, so rejections surface where the call happens. From vue it pulls defineComponent, ref, onErrorCaptured — the imports name exactly which library surface the snippet touches.
The return value is newly constructed — inputs are never handed back.
Watch out for
- Plan for an install step:
vueis a real dependency, resolved by the package manager. - The
await fetch(...)insetup()makes network reachability a runtime prerequisite — until the request resolves, the async setup never completes and Suspense keeps showing its fallback.
Statements that matter
const res = await fetch('https://api.example.com/posts');
posts.value = await res.json();
return { posts };
FAQ
- What does this need from the package registry?
- These are real dependencies: `vue`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.