0
0
VueHow-ToBeginner · 4 min read

How to Use Fetch API in Vue: Simple Guide with Examples

In Vue, you use the fetch API inside lifecycle hooks like onMounted to load data when a component appears. You call fetch with a URL, then handle the response with async/await or then to update your component's reactive state.
📐

Syntax

The fetch function takes a URL string and returns a promise that resolves to a response object. You usually call response.json() to get the data as JSON. In Vue, you place this inside onMounted to run when the component loads.

  • fetch(url): starts the request
  • await response.json(): parses JSON data
  • onMounted(() => { ... }): Vue hook to run code after component mounts
javascript
import { ref, onMounted } from 'vue';

const data = ref(null);

onMounted(async () => {
  const response = await fetch('https://api.example.com/data');
  data.value = await response.json();
});
💻

Example

This example shows a Vue component that fetches user data from an API when it loads and displays the user's name. It uses ref to store data reactively and onMounted to run the fetch call.

vue
<template>
  <div>
    <p v-if="user">User name: {{ user.name }}</p>
    <p v-else>Loading...</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const user = ref(null);

onMounted(async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    if (!response.ok) throw new Error('Network response was not ok');
    user.value = await response.json();
  } catch (error) {
    console.error('Fetch error:', error);
  }
});
</script>
Output
User name: Leanne Graham
⚠️

Common Pitfalls

Common mistakes when using fetch in Vue include:

  • Not handling errors, which can cause silent failures.
  • Forgetting to await response.json(), leading to unresolved promises.
  • Calling fetch outside lifecycle hooks, causing multiple or early requests.

Always use try/catch to handle errors and place fetch calls inside onMounted or similar hooks.

javascript
/* Wrong way: no error handling and no await on json() */
onMounted(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
      console.log(data);
    });
});

/* Right way: with async/await and error handling */
onMounted(async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Failed to fetch');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
});
📊

Quick Reference

  • Use onMounted to run fetch when component loads.
  • Always await both fetch and response.json().
  • Handle errors with try/catch or .catch().
  • Update reactive state with ref or reactive.
  • Check response.ok to confirm successful fetch.

Key Takeaways

Use fetch inside Vue's onMounted hook to load data when the component appears.
Always await both fetch and response.json() to get the data correctly.
Handle errors with try/catch to avoid silent failures.
Store fetched data in reactive refs to update the UI automatically.
Check response.ok to ensure the fetch was successful before using data.