TExcelTAD
Home › Vue › Vue HTTP Requests

Vue HTTP Requests

Most apps load data from a server: products, users, weather, messages. Vue itself has no special HTTP feature — you use the browser's fetch() (or a library like Axios) and store the result in reactive state. When the data arrives, the template updates automatically.

Because the playgrounds on this site run offline in a sandbox, the examples use a small fake API: functions that return Promises resolved after a delay, just like a real network call. The Vue code is exactly what you'd write with fetch.

A real request with fetch

js
import { ref, onMounted } from 'vue'

const posts = ref([])
const error = ref(null)

onMounted(async () => {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5')
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    posts.value = await res.json()
  } catch (e) {
    error.value = e.message
  }
})

Three things to remember about fetch:

Fact Consequence
It returns a Promise Use async/await or .then()
It only rejects on network failure Check res.ok yourself for 404/500 responses
The body must be parsed await res.json() (or .text(), .blob())

Loading, error and data states

Every request has three possible outcomes the UI must handle: still loading, failed, or succeeded. Try the "fail" checkbox:

html · try it yourself
<style>
  .user { padding: 6px 10px; border-bottom: 1px solid #eee; }
  .error { color: #b91c1c; }
</style>

<div id="app">
  <label><input type="checkbox" v-model="shouldFail"> make the next request fail</label>
  <button @click="load" :disabled="loading">Reload</button>

  <p v-if="loading">⏳ Loading users…</p>
  <p v-else-if="error" class="error">❌ {{ error }} <button @click="load">Try again</button></p>
  <div v-else>
    <div class="user" v-for="u in users" :key="u.id">{{ u.name }} — {{ u.city }}</div>
  </div>
</div>

<script type="module">
  import { createApp, ref, onMounted } from 'vue';

  // --- fake API (stands in for fetch('/api/users')) ---
  const DB = [
    { id: 1, name: 'An Tran', city: 'Hanoi' },
    { id: 2, name: 'Binh Le', city: 'Hue' },
    { id: 3, name: 'Cuc Vo', city: 'Can Tho' }
  ];
  function fakeGetUsers(fail) {
    return new Promise((resolve, reject) => {
      setTimeout(() => fail ? reject(new Error('Server responded 500')) : resolve(structuredClone(DB)), 700);
    });
  }

  createApp({
    setup() {
      const users = ref([]);
      const loading = ref(false);
      const error = ref(null);
      const shouldFail = ref(false);

      async function load() {
        loading.value = true;
        error.value = null;
        try {
          users.value = await fakeGetUsers(shouldFail.value);
          console.log('loaded', users.value.length, 'users');
        } catch (e) {
          error.value = e.message;
          console.log('request failed:', e.message);
        } finally {
          loading.value = false;
        }
      }

      onMounted(load);
      return { users, loading, error, shouldFail, load };
    }
  }).mount('#app');
</script>

Tip: Always reset error before a new request and set loading = false in finally, so the UI never gets stuck in the loading state.

Sending data (POST)

js
async function createTodo(text) {
  const res = await fetch('/api/todos', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text, done: false })
  })
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()          // the created item, with its new id
}

The playground simulates it with an optimistic update: the new item appears immediately and is marked as saved when the "server" confirms.

html · try it yourself
<div id="app">
  <form @submit.prevent="add">
    <input v-model.trim="text" placeholder="New todo"> <button :disabled="!text">Save</button>
  </form>
  <ul>
    <li v-for="t in todos" :key="t.tempId">
      {{ t.text }} <small>{{ t.id ? '✔ saved as #' + t.id : '⏳ saving…' }}</small>
    </li>
  </ul>
</div>

<script type="module">
  import { createApp, ref } from 'vue';

  let serverId = 100;
  const fakePost = (body) => new Promise(r => setTimeout(() => r({ ...body, id: ++serverId }), 900));

  createApp({
    setup() {
      const text = ref('');
      const todos = ref([]);
      let tempId = 0;

      async function add() {
        const item = { tempId: ++tempId, text: text.value, id: null };
        todos.value.push(item);                      // optimistic: show at once
        text.value = '';
        const saved = await fakePost({ text: item.text });
        todos.value.find(t => t.tempId === item.tempId).id = saved.id;
        console.log('server stored', JSON.stringify(saved));
      }
      return { text, todos, add };
    }
  }).mount('#app');
</script>

Refetching when something changes

Combine a request with watch to reload whenever a parameter changes — a category, a page number, a search term. { immediate: true } also runs it on start.

html · try it yourself
<div id="app">
  <button v-for="c in categories" :key="c" @click="category = c" :disabled="category === c">{{ c }}</button>
  <p v-if="loading">Loading {{ category }}…</p>
  <ul v-else><li v-for="p in products" :key="p">{{ p }}</li></ul>
</div>

<script type="module">
  import { createApp, ref, watch } from 'vue';

  const CATALOG = {
    tea: ['Green tea', 'Oolong', 'Earl Grey'],
    coffee: ['Espresso beans', 'Robusta', 'Cold brew'],
    snacks: ['Rice crackers', 'Dried mango']
  };
  const fakeGetProducts = (cat) => new Promise(r => setTimeout(() => r(CATALOG[cat]), 500));

  createApp({
    setup() {
      const categories = Object.keys(CATALOG);
      const category = ref('tea');
      const products = ref([]);
      const loading = ref(false);

      watch(category, async (cat) => {
        loading.value = true;
        const result = await fakeGetProducts(cat);
        if (cat === category.value) products.value = result;   // ignore late answers
        loading.value = false;
        console.log('fetched', cat);
      }, { immediate: true });

      return { categories, category, products, loading };
    }
  }).mount('#app');
</script>

A reusable useFetch composable

Request logic repeats in every component, so it's a perfect composable:

js
// composables/useFetch.js
import { ref, watchEffect, toValue } from 'vue'

export function useFetch(url) {
  const data = ref(null), error = ref(null), loading = ref(false)

  watchEffect(async () => {
    loading.value = true
    error.value = null
    try {
      const res = await fetch(toValue(url))          // re-runs when url (a ref/getter) changes
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      data.value = await res.json()
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  })
  return { data, error, loading }
}
js
const { data: user, loading } = useFetch(() => `/api/users/${props.id}`)
Library Why use it
fetch (built in) No dependency, enough for most apps
Axios Interceptors (auth headers), automatic JSON, timeouts
VueUse useFetch Ready-made composable with abort and refetch
TanStack Query (Vue Query) Caching, background refresh, retries, pagination

Note: Browsers block requests to other domains unless the server allows it with CORS headers. During development, Vite's server.proxy option can forward /api calls to your back-end to avoid CORS issues.

Test yourself

Does fetch() reject its Promise when the server answers with status 404?

  1. Yes, always
  2. No — you must check res.ok or res.status
  3. Only for POST requests
  4. Only in Vue

Which lifecycle hook is a common place to start loading data in a component?

  1. onUnmounted
  2. onMounted (or directly in setup)
  3. onUpdated
  4. onBeforeUnmount

Why set loading.value = false in a finally block?

  1. It is faster
  2. So it runs whether the request succeeded or failed
  3. finally is required with await
  4. To cancel the request