Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 87 ยท Data Fetching

Fetching Data

Fetch data in Vue 3 with onMounted and watch. Model loading, error and data state, refetch when an id changes, avoid race conditions with AbortController and test it against a mock API.

Almost every real page needs data from a server: a profile, a list of posts, search results. Vue has no special fetching feature. You use the browser's fetch (see Fetch) together with the reactivity tools you already know: refs hold the result, onMounted or watch decide when to ask, and a template shows one of three views depending on the state.

Doing this well means more than calling fetch. A request can be slow, it can fail, and when the input changes quickly several requests can be in flight at once and arrive out of order. This lesson builds the pattern step by step and fixes each of those problems.

Sandbox note: a mock API

The live examples on this site cannot call a real server, so they use a small function, fakeFetch, that returns a promise after a delay and an object shaped like a real Response (ok, status and json()). The code that uses it is written exactly as it would be with the real fetch: replace fakeFetch with fetch and a real URL and it works the same. fakeFetch also understands an AbortSignal, so the cancellation examples behave like the real thing.

The three states of a request

At any moment a request is in exactly one situation, and the UI must handle all of them:

flowchart LR
    I["Idle"] --> L["Loading"]
    L -->|"response ok"| D["Data"]
    L -->|"error or bad status"| E["Error"]
    E -->|"retry"| L
    D -->|"refetch"| L

Keep loading, error and data as three refs, and make sure each request sets all of them.

Two details trip people up. First, fetch only rejects its promise for network failures. A 404 or 500 response resolves normally, so you must check response.ok and throw yourself. Second, always reset the old error when you start again, and always clear loading in a finally block so a failure cannot leave the spinner on forever.

Loading, error and data with a retry button

The first request fails on purpose, so you see the error state; press Retry and the second request succeeds. In a real project the same code goes into a component, and it is a good candidate for a composable when several components need it.

Why onMounted and not the top level of setup()? Code at the top level also runs during server-side rendering, where a browser-style fetch to a relative URL often makes no sense. onMounted runs in the browser only. If you later use a framework like Nuxt, it gives you dedicated data-fetching helpers for the server case.

Refetching when something changes

Many requests depend on an input: the selected user, the current page, a search term. The tool for "run this whenever that changes" is watch. Set immediate: true and the callback also runs once at the start, so you do not need a separate onMounted call.

JavaScript
watch(userId, async (newId) => {
  loading.value = true;
  // ...fetch /api/users/${newId}...
}, { immediate: true });

There is a catch. The user can click faster than the server answers.

Race conditions

Suppose the user selects user 1 (a slow response) and immediately selects user 2 (a fast one). Two requests are in flight. The reply for user 2 arrives first and is shown. Then the old reply for user 1 arrives and overwrites it. The page now says "user 1" although the selection says "user 2".

sequenceDiagram
    participant U as User
    participant C as Component
    participant S as Server
    U->>C: select user 1
    C->>S: GET user 1 (slow)
    U->>C: select user 2
    C->>S: GET user 2 (fast)
    S-->>C: reply for user 2
    Note over C: shows user 2
    S-->>C: reply for user 1 (late)
    Note over C: stale data overwrites user 2

Responses can arrive in a different order from the requests that caused them.

The fix is to cancel the request that is no longer wanted. A watcher callback receives a third argument, onCleanup, which registers a function that Vue runs before the next run of the callback and when the watcher is stopped. Create an AbortController per run, pass its signal to fetch and abort it in the cleanup. (In Vue 3.5 you can also import onWatcherCleanup and call it from inside the callback, which is useful in helper functions.)

The example runs both versions side by side from the same selection. Click User 1, then User 2 right away, and watch the two panels. User 1 takes 900 ms to answer, user 2 takes 200 ms, and user 3 always fails.

Race condition: unguarded versus aborted

After User 1 then User 2, the unguarded panel first shows Grace Hopper and then, about 900 ms after the first click, changes to Ada Lovelace with a red "(stale!)" label even though id 2 is selected. The guarded panel shows only Grace Hopper: when the id changed, the cleanup aborted the first request, fakeFetch rejected with an AbortError, and the catch block ignored it on purpose.

Two details in useUser are worth copying. An abort is not a failure, so it is handled before the error branch. And loading is only cleared if this run was not cancelled, because a newer run has already set it back to true.

Fetching with real code

Here is the same pattern as a Single-File Component with the real fetch. It is read-only on this site because the runner cannot reach a server:

VUE
<script setup>
import { ref, watch } from "vue";

const userId = ref(1);
const user = ref(null);
const error = ref(null);
const loading = ref(false);

watch(userId, async (id, oldId, onCleanup) => {
  const controller = new AbortController();
  onCleanup(() => controller.abort());

  loading.value = true;
  error.value = null;
  try {
    const response = await fetch(`/api/users/${id}`, { signal: controller.signal });
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    user.value = await response.json();
  } catch (e) {
    if (e.name !== "AbortError") {
      error.value = e.message;
    }
  } finally {
    if (!controller.signal.aborted) {
      loading.value = false;
    }
  }
}, { immediate: true });
</script>

If the component is removed while a request is running, Vue stops the watcher and runs the cleanup too, so the request is cancelled and nothing tries to update an unmounted component.

Using Axios instead of fetch

Axios is a popular HTTP client library that you install with npm (npm install axios). It is not part of Vue, and you never need it, but many Vue projects use it because it packs the chores you otherwise repeat around fetch into one object:

Task Plain fetch Axios
HTTP error status (404, 500) Resolves normally; you must check response.ok Rejects the promise for any status outside 2xx
Reading JSON await response.json() Already parsed in response.data
Sending JSON JSON.stringify and a Content-Type header yourself Pass an object, it is serialized for you
Base URL and shared headers Repeat them in every call Set once on an instance
Run code on every request or response Write a wrapper function Interceptors
Timeout AbortSignal.timeout(ms) timeout option
Cancel AbortController The same AbortController, via signal

Here is how a real project usually wires it up. This is read-only code, because the runner cannot install packages:

JavaScript
// src/api.js
import axios from "axios";

export const api = axios.create({
  baseURL: "https://api.example.com/v1",
  timeout: 8000,
  headers: { Accept: "application/json" },
});

// Runs before every request: attach the token
api.interceptors.request.use((config) => {
  const token = sessionStorage.getItem("token");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Runs for every response: turn failures into one friendly Error
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (axios.isCancel(error)) {
      return Promise.reject(error); // the caller aborted on purpose
    }
    const status = error.response?.status;
    const message = status === 404 ? "Not found" : status ? `Server error ${status}` : "Network problem";
    return Promise.reject(new Error(message));
  },
);

Inside a component or composable you then write const { data } = await api.get(/users/${id}, { signal }). Cancelling works exactly as in the race-condition section: create an AbortController per run of the watcher, pass controller.signal and abort it in onCleanup. A cancelled Axios request rejects with an error for which axios.isCancel(error) is true (its code is "ERR_CANCELED"), so your catch block must ignore it the way ours ignored AbortError.

You can see why instances and interceptors are handy without installing anything. The example below builds a tiny stand-in client on top of fakeFetch with the same ideas: a base URL, a request interceptor that adds a header, and a response interceptor that converts bad statuses into errors. It is not Axios, only a model of how it behaves.

An Axios-like client with interceptors (stand-in)

User 1 succeeds and the echoed sentAuth field shows that the request interceptor added the header without the calling code knowing. User 2 and the crash button both reach your catch block with the friendly message from the response interceptor, so components never have to inspect status codes.

Which should you choose? fetch is built in, small and enough for most apps, especially with a wrapper like the one in composable patterns. Axios earns its place when you need interceptors, many shared defaults or upload progress events (onUploadProgress). Whichever you pick, keep the HTTP calls in one module (api.js) and let composables call that module, so components never import the client directly.

Practical advice

  • Debounce typing. For search-as-you-type, wait a short moment after the last keystroke before fetching, so you do not send a request per letter. See composable patterns for useDebounce.
  • Show old data while loading when it helps. Replacing the content with a spinner on every page change feels jumpy; keeping the previous list and dimming it feels smoother.
  • Do not store derived data. If a list is filtered or sorted in the browser, use a computed property over the fetched list rather than a second ref you must keep in sync.
  • Reach for a library when needs grow. Caching, deduplicating identical requests, background refresh and retries are tedious to hand-write. Libraries such as TanStack Query for Vue handle them, and the useFetch helper in VueUse covers simple cases. The React lesson on fetching discusses the same trade-off.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A fetch call returns a response with status 404. What happens to the promise?

    fetch only rejects on network failures. HTTP error statuses still resolve, so check response.ok (or response.status) and throw your own error.
  2. 2. Why is the loading flag reset inside a finally block?

    finally runs after both success and failure, so an error cannot leave the interface stuck in a loading state.
  3. 3. What is the purpose of onCleanup in a watch callback when fetching?

    Vue calls the registered cleanup before the next run (and when the watcher stops). Aborting an AbortController there cancels the request that is no longer needed.
  4. 4. After an AbortController aborts a fetch, the promise rejects with an AbortError. How should you treat it?

    An abort means a newer request replaced this one. It is not a real failure, so skip the error state and leave the loading flag to the newer run.

Summary

  • Model a request with three refs, loading, error and data, and let the template show one of the three views.
  • fetch does not reject on HTTP error statuses: check response.ok, and clear loading in finally.
  • Start requests in onMounted for one-off data, or in a watch (with immediate: true) when they depend on changing input.
  • Responses can arrive out of order. Abort the previous request using the onCleanup argument and an AbortController, and treat AbortError as expected.
  • Use a library once you need caching, deduplication or retries.

Next: Custom Directives