You order at Mrs. Sri's stall. The waiter says "it's cooking". A few minutes later he comes back with your order, or comes back and says "sorry, it's sold out". A good waiter never leaves you staring at an empty table without a word.
A page that gets data from a server should be just as polite. Fetching data means asking a server for data, such as the stall's menu list, and then showing it. The message that asks for the data is called a request, and the answer is called a response. A request takes time and can fail. So the component holds three states: still loading (loading), failed (error), and succeeded (data). They match the waiter's messages: "it's cooking" is loading, "sorry, it's sold out" is error, and the order that arrives is the data.
Three states: loading, error, data
In this code, the component asks /api/menu for the menu list. /api/menu is an address on the server that answers with the menu list:
const menu = ref([])
const loading = ref(true)
const error = ref(null)
onMounted(async () => {
try {
const res = await fetch("/api/menu")
if (!res.ok) throw new Error("HTTP " + res.status)
menu.value = await res.json()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
})
---template---
<p v-if="loading">Loading menu...</p>
<p v-else-if="error">Failed: {{ error }}</p>
<ul v-else>
<li v-for="m in menu" :key="m.id">{{ m.name }} · ${{ m.price }}</li>
</ul>
This table shows what the three states hold over time. The numbers 200 and 500 are status codes in the response: 200 means success, 500 means an error on the server.
| Time | loading |
error |
menu |
Shown |
|---|---|---|---|---|
| component mounted | true | null | [] | Loading menu... |
| 0.8 seconds, the server answers 200 | false | null | 3 menus | Fried Rice · $15, Chicken Noodles · $12, Iced Tea · $5 |
| or the server answers 500 | false | "HTTP 500" | [] | Failed: HTTP 500 |
onMountedruns after the component is on screen, the usual place to start a request. Its callback may beasync: anasyncfunction may useawaitinside it.fetch(url)is a function built into the browser that sends a request.await fetch(url)waits for the response to arrive, andresis that response.await res.json()waits for the response's contents (its body) to be read, then turns them into JavaScript data, here an array of menu items. Both needawait.tryholds the code that can fail. If something insidetryfails, JavaScript jumps directly tocatch, andeholds the error.finallyalways runs, success or failure. Soloadingis sure to go back tofalse.v-if,v-else-if,v-elsepick exactly one of the three views.- In a real
<script setup>, import first:import { ref, onMounted } from "vue". In the exercise editor they are already available.
fetch returns a Promise
fetch() doesn't return data. It returns a Promise: a promise that the result arrives later. await waits until that promise is kept, then gives you the result. Without await, menu.value holds that Promise, not the menu list. v-for finds no items in a Promise, so the list stays empty, with no error. menu.length is undefined too. Write await in two places, inside an async function: const res = await fetch(...) and then menu.value = await res.json().
In the exercise editor, you can't write await outside an async function. The editor runs your script as the body of a plain function, so the browser stops with SyntaxError: await is only valid in async functions and the top level bodies of modules. Put the await inside the callback onMounted(async () => { ... }).
fetch doesn't fail on 404 or 500
fetch only fails (jumps to catch) when the request can't happen at all, for example when the internet is down. A 404 (not found) or 500 (an error on the server) response is still a response. To know whether the response succeeded, check res.ok: true for status 200 to 299, false for any other status. That is why the first code in this lesson has the line if (!res.ok) throw new Error(...). When res.ok is false, throw throws an error you made yourself, so JavaScript jumps to catch. Without that line, the body of an error response, like { "message": "Server busy" }, goes into menu, and the page looks broken without any message.
In the exercise editor
The exercises don't use a real server. The second one uses a fake server, fetchData(), which answers like fetch after 0.05 seconds:
const items = ref([])
const loading = ref(true)
const error = ref(null)
const fetchData = () =>
new Promise((resolve) => {
setTimeout(() => resolve({
ok: true,
status: 200,
json: () => Promise.resolve(["Data 1", "Data 2", "Data 3"]),
}), 50)
})
onMounted(async () => {
try {
const res = await fetchData()
if (!res.ok) throw new Error("HTTP " + res.status)
items.value = await res.json()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
})
---template---
<div>
<p v-if="loading" id="loading">Loading...</p>
<p v-else-if="error" id="error">Failed: {{ error }}</p>
<ul v-else id="data">
<li v-for="item in items" :key="item">{{ item }}</li>
</ul>
</div>
- The first exercise:
loadingstartstrue,onMountedmakes itfalse, and<p id="status">readsData ready!(before that,Loading...). - The second exercise is the code above.
fetchData()and the template are already in the starter code, so you only write theonMounted. The checker reads three items fromv-for,Data 1at the top andData 3at the bottom. Then the checker looks forawait fetchData(,res.ok,catchandfinallyin your code.itemsmust still start atref([]). - Want to try writing
fetchcode in the Playground? The Lab on this page opens a version with a fake server: a home-madefetchfunction that answers with a response (aResponse) after a pause.
📌 Fetching again when the id changes
The detail page fetches /api/menu/1, then the customer picks menu 2. A new request is sent through watch. The problem is that responses don't always arrive in order: a request sent later can be answered first.
| Time | Event | Shown with no guard |
|---|---|---|
| 0 | pick Fried Rice, request /api/menu/1 (slow) |
Loading menu... |
| 0.2 seconds | pick Chicken Noodles, request /api/menu/2 (fast) |
Loading menu... |
| 0.5 seconds | the response for menu 2 arrives | Chicken Noodles |
| 1.5 seconds | the response for menu 1 arrives last | Fried Rice, though Chicken Noodles is picked |
The guard: mark the old request as stale (its answer is no longer needed) through onCleanup, the third argument of the watch callback:
watch(id, async (newVal, oldVal, onCleanup) => {
let stale = false
onCleanup(() => { stale = true })
loading.value = true
error.value = null
try {
const res = await fetch("/api/menu/" + newVal)
if (!res.ok) throw new Error("HTTP " + res.status)
const data = await res.json()
if (!stale) menu.value = data
} catch (e) {
if (!stale) error.value = e.message
} finally {
if (!stale) loading.value = false
}
}, { immediate: true })
- Vue runs the function inside
onCleanupright before the next callback. So as soon asidchanges, the old request'sstalebecomestrue, and that old request's result is ignored. - To really cancel the request on the network, use
AbortController: pass{ signal: controller.signal }tofetch, then callcontroller.abort()inonCleanup. A cancelledfetchfails with an error namedAbortError. awaitwritten directly in<script setup>(outside any function) makes the component async. An async component only shows inside<Suspense>, a built-in Vue component that waits for async components. Without<Suspense>, the component isn't rendered, and in development mode the console writessetup function returned a promise, but no <Suspense> boundary was found in the parent component tree.For beginners,onMountedwith a loading state is safer.
Other options. This lesson writes fetch itself so you understand the basics. In real projects you will also see the ways below (versions from npm, 15 November 2026):
| Way | When to pick it |
|---|---|
Your own composable, a useFetch(url) that returns { data, error } |
several components repeat the same code. The Vue docs show one on the Composables page |
useFetch from VueUse (@vueuse/core 15.0.0) |
a ready-made composable, with isFetching and abort included |
TanStack Query (@tanstack/vue-query 5.107.1) or Pinia Colada (@pinia/colada 1.4.9) |
the same data is used on many pages. Results are kept in a cache (saved results that can be used again), and identical requests are merged into one |
Nuxt's useFetch (4.6.4) |
your app is built with Nuxt (a framework built on top of Vue), which also fetches data on the server |
⚠️ Why is the list empty, or does it keep loading?
data.value = fetch(...)withoutawaitstores a Promise, not data, so the list stays empty. Wait forfetchandres.json()withawait.- 404 and 500 don't go to
catch. Checkres.ok, and throw an error yourself when!res.ok. loading.value = falsewritten only on the success path keeps the loading text on screen when the request fails. Put it infinally.- An old response can overwrite the new one. Mark the old request through
onCleanup, or cancel it withAbortController. - Data filled in as the starting value doesn't pass the exercise. The exercise checks for an
onMounted(that writes.value =(or.push() inside it, and that the list is made withv-for.
TL;DR: Get data from a server with fetch (a function built into the browser that sends a request, a message that asks the server for something) inside onMounted(async () => { ... }). The component holds three states: loading (still loading), error (failed), and the data (succeeded). The template picks one of them with v-if / v-else-if / v-else. fetch returns a Promise (a promise that the result arrives later), so wait for the result with await: await fetch(...) gives the response (the server's answer), then await res.json() reads its contents. fetch doesn't fail on status codes 404 or 500, so check res.ok, which is true only for status 200 to 299. Turn loading off in finally, which always runs. When the request is sent again each time id changes, responses can arrive out of order. So ignore old responses through onCleanup in watch, or cancel the old request with AbortController.
⚡ Three states: loading, error, data
Write:
const menu = ref([])
const loading = ref(true)
const error = ref(null)
onMounted(async () => {
try {
const res = await fetch("/api/menu")
if (!res.ok) throw new Error("HTTP " + res.status)
menu.value = await res.json()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
})
---template---
<p v-if="loading">Loading menu...</p>
<p v-else-if="error">Failed: {{ error }}</p>
<ul v-else>
<li v-for="m in menu" :key="m.id">{{ m.name }} · ${{ m.price }}</li>
</ul>
Meaning: A component that gets data from a server holds three states: loading (still loading), error (failed), and the data (succeeded), here menu. The request (the message that asks the server for data) starts in onMounted. fetch sends the request, await waits for the answer (the response, here res), and res.json() reads the contents of that answer. try holds the code that can fail, catch catches a failure, and finally always runs, so loading is sure to go back to false. v-if, v-else-if and v-else pick exactly one of the three views.
⚡ fetch returns a Promise
Guess first: data.value = fetch('/api/data'), with no await. Does the data appear in the list?
Never. fetch() returns a Promise, a promise that the result arrives later, so data.value holds the Promise, not the data.
Meaning: await waits for a Promise until its result arrives, and you can only use it inside an async function. Write await in two places: await fetch(...) and then await res.json().
⚡ 404 and 500 aren't failures to fetch
Write:
if (!res.ok) throw new Error("HTTP " + res.status)
Meaning: fetch only fails when the request can't happen at all, for example when the internet is down. A response with status 404 (not found) or 500 (an error on the server) is still a response. res.ok is true only for status 200 to 299. So when res.ok is false, throw an error yourself with throw, so that catch handles it.