Data fetching in Vue
Fetch in setup, track loading and error with refs, refetch when inputs change, cancel stale requests, and wrap it all in a useFetch composable.
Watchers with watch and watchEffectComposablesAsync components and Suspense
Data fetching in Vue
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A fetch in Vue is three pieces of reactive state, data, error and loading, plus a function that sets them; the template renders from whichever state is current.
- Kicking off a fetch directly in script setup starts it as early as possible; onMounted is only needed when the request must not run during server rendering or needs the DOM.
- When a request depends on reactive input such as a route param, a watcher with immediate: true or watchEffect refetches it whenever that input changes.
- A refetch can race an earlier, slower request; aborting the old request in onWatcherCleanup with an AbortController keeps the newest response in charge.
- A useFetch composable that accepts a ref, getter, or plain value and reads it with toValue turns this pattern into one reusable line per component.
- Hand-rolled fetching still lacks a shared cache, deduplication, and background refetching, which is the gap a query library fills.
Three refs and a promise
Vue has no built-in data-fetching API, and doesn’t need one. Fetching data is an asynchronous operation that, at any moment, is in one of three states: still loading, failed, or done with data. In Vue, each of those becomes a ref, and the template renders from whichever one is set.
The fetch call itself is plain JavaScript, covered in the frontend roadmap’s fetch and working with APIs. async/await comes from the JavaScript roadmap. What’s Vue-specific is how those pieces meet reactivity.
<script setup>
import { ref } from 'vue'
const posts = ref(null)
const error = ref(null)
const loading = ref(true)
async function load() {
try {
const res = await fetch('/api/posts')
if (!res.ok) throw new Error(`HTTP ${res.status}`)
posts.value = await res.json()
} catch (err) {
error.value = err
} finally {
loading.value = false
}
}
load()
</script>
<template>
<p v-if="loading">Loading…</p>
<p v-else-if="error">Couldn't load posts: {{ error.message }}</p>
<ul v-else>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</template>
Note the res.ok check. fetch only rejects on network failure, not on a 404 or 500, so without it a server error becomes “data”.
Setup or onMounted?
Calling load() directly in <script setup> starts the request while the component is still being created, which is the earliest possible moment. Many tutorials wrap it in onMounted out of habit from other frameworks. In a client-only app the difference is small: the request starts a few milliseconds later.
The difference that matters is server-side rendering. Code in setup runs on the server too; onMounted never does. If a request should happen only in the browser, because it reads localStorage or needs the DOM, put it in onMounted. Otherwise, setup is fine. Fetching during SSR properly, so the server waits for the data and hands it to the client, is a framework concern; Nuxt’s useFetch and useAsyncData handle it and are covered in data fetching in Nuxt.
Refetching when inputs change
Real requests depend on something: a route param, a search box, a page number. When that input changes, the data must be refetched. This is what watchers are for.
<script setup>
import { ref, watch, onWatcherCleanup } from 'vue'
const props = defineProps({ userId: String })
const user = ref(null)
const error = ref(null)
const loading = ref(false)
watch(
() => props.userId,
async (id) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort())
loading.value = true
error.value = null
try {
const res = await fetch(`/api/users/${id}`, { signal: controller.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
user.value = await res.json()
} catch (err) {
if (err.name !== 'AbortError') error.value = err
} finally {
if (!controller.signal.aborted) loading.value = false
}
},
{ immediate: true },
)
</script>
immediate: true runs the callback once at the start, so the same code handles the first load and every later change.
The race you didn’t ask for
The AbortController lines are there because of a race. Picture a user clicking from user 1 to user 2. Two requests are now in flight. If the first one is slower, it lands after the second and overwrites user 2 with user 1. The page shows the wrong person, with no error anywhere.
Think of it like a restaurant kitchen: a customer changes their order, and if the kitchen doesn’t throw out the first ticket, two plates come out and the waiter delivers whichever is ready last.
onWatcherCleanup (Vue 3.5+) registers a function that runs right before the watcher’s callback runs again, or when the watcher stops. Aborting there cancels the stale request; its fetch rejects with an AbortError, which the catch ignores. One rule: call onWatcherCleanup before the first await, because Vue only knows which watcher is running during the synchronous part of the callback. Older code uses the callback’s third argument, onCleanup, for the same thing.
Wrapping it in a composable
Writing those refs and that watcher in every component gets old fast. A composable packages the pattern, and the Vue docs build almost exactly this one:
// composables/useFetch.js
import { ref, watchEffect, toValue, onWatcherCleanup } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(false)
watchEffect(async () => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort())
const target = toValue(url) // tracked: a ref or getter triggers refetch
loading.value = true
error.value = null
try {
const res = await fetch(target, { signal: controller.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
data.value = await res.json()
} catch (err) {
if (err.name !== 'AbortError') error.value = err
} finally {
if (!controller.signal.aborted) loading.value = false
}
})
return { data, error, loading }
}
const { data: user, loading } = useFetch(() => `/api/users/${props.userId}`)
The key line is toValue(url), read before the first await so that watchEffect tracks it. It accepts a plain string, a ref, or a getter. Pass a getter and the composable refetches whenever the props it reads change. VueUse ships a fuller useFetch along these lines, with abort, timeouts, interceptors, and a refetch option for reactive URLs.
Awaiting in setup with Suspense
There’s one more option. <script setup> allows top-level await:
<script setup>
const res = await fetch('/api/posts')
const posts = await res.json()
</script>
This turns the component into an async component. It renders nothing until the promise settles, and a <Suspense> ancestor shows a fallback meanwhile. It’s tidy — no loading ref at all — but loading and errors move up to the boundary, it doesn’t refetch on its own, and <Suspense> is still marked experimental in the Vue docs. It suits data a page can’t render without; for anything that changes while the page is open, the watcher pattern is a better fit.
What hand-rolled fetching still lacks
Everything above works, and plenty of apps ship with nothing more. But notice what isn’t there. Two components calling useFetch('/api/user') make two requests and hold two copies. Leaving a page and coming back refetches from scratch, showing a spinner for data you had a second ago. Nothing refetches when the user returns to the tab. Nothing tells the list to update after you edit an item. That is the case React’s the case for a data-fetching library makes, and it applies to Vue word for word.
What the video covers
The embed is a ten-minute stretch (1:59:50 to 2:09:50) of Brad Traversy’s 2024 Vue crash course, the same course the Vue Router fundamentals lesson uses. Over the “Fetch Data For JobListings”, “reactive() Function”, “JobListings Refactor To reactive()” and “Vue Spinner” chapters, he fetches a job list from a local json-server API inside onMounted in a <script setup> component, with the request in a try/catch. He then folds the list and an isLoading flag into one reactive() object and shows a spinner while the flag is true. That is the “three refs and a promise” starting point, held in one reactive object instead of separate refs, and with errors only logged to the console rather than shown.
It stops there. It doesn’t render an error state, refetch when an input changes, cancel stale requests, wrap the logic in a composable, or use Suspense. Those are the parts the watcher, race, and composable sections above add, and they are what separates a demo fetch from one that holds up in a real app.
Where this fits
The next lesson, TanStack Query for Vue, replaces the hand-rolled composable with a real query cache.
Check yourself
A user page watches route.params.id and fetches the user each time it changes. The user clicks from user 1 to user 2 quickly, and the page ends up showing user 1. What happened?
Both requests were in flight at once and the request for user 1 finished last, overwriting the newer result for user 2. The fix is to cancel or ignore the previous request when the input changes, for example by creating an AbortController per run and calling controller.abort() in onWatcherCleanup.
What changes when a component uses top-level await in its script setup block?
The component becomes an async component: its setup doesn't finish until the awaited promise settles, so it renders nothing until then. It must have a Suspense boundary above it, which shows a fallback while the data loads. Errors must be caught by an error boundary such as onErrorCaptured in an ancestor.
Why should a useFetch composable read its URL argument with toValue inside watchEffect, rather than reading url.value once at the top?
Reading the value once captures a single string, so the composable never notices later changes. Calling toValue(url) inside watchEffect makes the ref or getter a tracked dependency, so the effect reruns and refetches whenever it changes, while plain strings still work.
Two components on the same page both call your useFetch('/api/user'). How many requests go out, and why does that matter?
Two. Each call creates its own refs and its own fetch, with no shared cache between them. On a busy page this means duplicate requests, and the two components can show different versions of the same data, which is one of the main reasons to reach for a query library.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.