Learn Vue.js ยท 11/13

Real-World Vue: Fetching and Managing Data

7 min read

๐Ÿ‘‹ Welcome to the Real World

building a To-Do list with hardcoded items like const todos = ['Eat', 'Sleep', 'Code'] is safe, cozy, and... completely useless in the real world. Modern web applications are dynamic. They need to talk to servers, fetch user profiles, load tweets, and occasionally crash because the WiFi dropped.

In this module, we are moving from "Hello World" to "Hello Server". We will learn how to pull data from the outside world into your Vue application, handle the inevitable errors (because servers are moody), and ensure your user isn't staring at a blank white screen while data travels across the ocean.


1. Calling APIs with Fetch/Axios inside Vue ๐Ÿ“ž

Definition

API (Application Programming Interface): A set of protocols and tools that allows different software applications to communicate with each other. In frontend development, this usually means sending a request to a URL and getting back JSON data.

The Problem

Your Vue component lives in the browser. Your data lives in a database on a server. They are separated by the internet. You need a mechanism to bridge this gap.

The Solution

We use HTTP clients. The two heavyweights in the ring are:

  1. Fetch API: Built into the browser. Lightweight, no installation needed.
  2. Axios: A third-party library. Automatic JSON transformation, better error handling, and widely used in the industry.

Industry Standard: Why Axios?

While fetch is great, axios creates a smoother developer experience. It automatically converts the response to JSON (saving you a line of code), handles HTTP error status codes (like 404 or 500) inside the catch block automatically, and supports request cancellation.

Fun Fact: The first webcam was invented at the University of Cambridge to check if the coffee pot was full without getting up. That was basically the first "API" callโ€”checking the status of a resource remotely! โ˜•๏ธ

๐Ÿ› ๏ธ Setting Up Axios

First, let's install it.

bash
npm install axios

๐Ÿ’ป Code Example: The Basic Fetch

Let's look at a simple implementation using Vue's Composition API (<script setup>).

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

// 1. Create a reactive variable to hold the data
const userData = ref(null);

// 2. Define a function to get the data
const getUser = async () => {
  // We use async/await because the internet takes time
  const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
  
  // Axios puts the actual data inside a .data property
  userData.value = response.data;
  console.log("Data arrived! ๐ŸŽ‰", userData.value);
};
</script>

<template>
  <div>
    <h1>User Profile</h1>
    <button @click="getUser">Load User</button>
    
    <!-- Only show this if we actually have data -->
    <div v-if="userData">
      <p>Name: {{ userData.name }}</p>
      <p>Email: {{ userData.email }}</p>
    </div>
  </div>
</template>

2. Handling Loading and Error States Gracefully โณ๐Ÿ›

The Problem

Network requests are asynchronous. They take time. Between the moment the user clicks "Load" and the moment data arrives, there is a gap. If you don't handle this, the app looks broken (or unresponsive). Also, sometimes the API fails (server down, bad internet). If you don't catch errors, your app crashes.

The Solution

We treat the network request as a state machine with three main states:

  1. Loading: The request is in flight. Show a spinner.
  2. Success: We have data. Show the content.
  3. Error: Something went wrong. Show a helpful message.

Real-Life Analogy

Imagine ordering a pizza ๐Ÿ•.

  • Loading: You are watching the tracker (Pizza is in the oven).
  • Success: The doorbell rings (Pizza is here).
  • Error: The delivery driver drops your pizza in a puddle. You need to know this happened so you can order another one (or cry).

๐Ÿ’ป Code Example: The Robust Pattern

This is the standard pattern you will see in almost every production Vue app.

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

const posts = ref([]);
const isLoading = ref(false); // Are we waiting?
const error = ref(null);      // Did something break?

const fetchPosts = async () => {
  // Reset states before starting
  isLoading.value = true;
  error.value = null;

  try {
    // Attempt the dangerous operation
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    posts.value = response.data; 
  } catch (err) {
    // Catch the error if the server explodes
    console.error("Oops!", err);
    error.value = "Failed to load posts. Please try again later.";
  } finally {
    // ALWAYS turn off the loader, success or fail
    isLoading.value = false;
  }
};
</script>

<template>
  <div>
    <button @click="fetchPosts" :disabled="isLoading">
      {{ isLoading ? 'Loading...' : 'Get Posts' }}
    </button>

    <!-- State 1: Error -->
    <div v-if="error" class="error-msg">
      ๐Ÿ”ด {{ error }}
    </div>

    <!-- State 2: Loading -->
    <div v-else-if="isLoading" class="loader">
      โณ Fetching data from the cloud...
    </div>

    <!-- State 3: Success -->
    <ul v-else>
      <li v-for="post in posts" :key="post.id">
        {{ post.title }}
      </li>
    </ul>
  </div>
</template>

<style>
.error-msg { color: red; background: #fee; padding: 10px; }
.loader { color: gray; font-style: italic; }
</style>

3. Component Lifecycle Hooks: The Best Time to Fetch โฐ

Definition

Lifecycle Hooks: Special methods that run at specific stages of a component's life (creation, mounting, updating, destruction).

The Problem

In the previous examples, we used a button to trigger the fetch. But usually, when you visit a "Profile Page," you expect the profile to load automatically, without clicking anything.

Where do we put the code to run automatically?

  • If we put it in the setup() body directly (without async), it runs before the component is even attached to the screen.
  • If we put it in updated, it might loop infinitely every time data changes.

The Solution: onMounted

The onMounted hook is the industry standard for initial data fetching. It runs exactly once, immediately after the component has been added to the DOM (Document Object Model).

Analogy: onMounted is like the moment you walk into a restaurant and sit down. That is the correct time to ask for a menu (fetch data). You don't ask for the menu while you are still parking the car (setup start), and you don't ask for it every time you take a sip of water (updated).

๐Ÿ’ป Code Example: Automatic Fetching

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

const dogImage = ref(null);

const fetchDog = async () => {
  const response = await axios.get('https://dog.ceo/api/breeds/image/random');
  dogImage.value = response.data.message;
};

// This runs automatically when the component is ready!
onMounted(() => {
  console.log("Component mounted. Unleashing the hounds...");
  fetchDog();
});
</script>

<template>
  <div>
    <h2>Daily Doggo</h2>
    <img v-if="dogImage" :src="dogImage" alt="A cute dog" width="300" />
    <p v-else>Looking for a dog...</p>
  </div>
</template>

4. Using Vue's Suspense Component with Async Setup ๐Ÿ”ฎ

Definition

Suspense: A built-in Vue component that orchestrates async dependencies in a component tree. It allows you to wait for nested async components to resolve before rendering the UI.

The Problem

Managing isLoading and error states in every single component gets tedious. You end up with "v-if loading" boilerplate code everywhere. What if the parent component could just say, "Don't show this child until it's ready"?

The Solution

Vue 3 allows us to use top-level await inside <script setup>. If a component uses await at the top level (outside a function), it becomes an Async Component.

However, an async component must be wrapped in a <Suspense> boundary in the parent.

Warning: While Suspense is stable enough that many production apps use it, the Vue team still lists it as "Experimental" in some docs. Use it, but know that the API might tweak slightly in the distant future.

๐Ÿ’ป Code Example

The Child (AsyncUser.vue):
Notice there is no .then() and no function wrapper. We just await right in the setup!

vue
<script setup>
import axios from 'axios';

// Top-level await! This pauses component rendering.
const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
const user = response.data;
</script>

<template>
  <div class="user-card">
    <h3>{{ user.name }}</h3>
    <p>{{ user.email }}</p>
  </div>
</template>

The Parent (App.vue):
The parent handles the waiting state using <Suspense>.

vue
<template>
  <div>
    <h1>Suspense Demo</h1>
    
    <Suspense>
      <!-- #default: What to show when data is ready -->
      <template #default>
        <AsyncUser />
      </template>

      <!-- #fallback: What to show while waiting -->
      <template #fallback>
        <div class="shimmer-loader">
          Loading User Profile... ๐Ÿšง
        </div>
      </template>
    </Suspense>
    
  </div>
</template>

<script setup>
import AsyncUser from './AsyncUser.vue';
</script>

Why use this?

It decouples the fetching logic from the loading UI logic. The child component worries about data; the parent component worries about the user interface experience (spinners/skeletons).


๐Ÿ“š References & Further Reading

Challenge

Challenge: Asynchronous Product Component with Suspense

You are tasked with building a Vue component that fetches and displays data for a single product. This component must fetch its data asynchronously upon setup. You will use Vue's <Suspense> component to manage the user experience while the data is being fetched.

Requirements:

  1. Inside the <script setup> block, import the axios library.
  2. Perform an HTTP GET request to the following URL to fetch product data: https://dummyjson.com/products/1.
  3. Use a top-level await to handle the asynchronous nature of the request. This will turn your component into an async component, a prerequisite for using <Suspense>.
  4. From the response, extract the title and description properties of the product.
  5. In the <template> block, within the #default slot of the <Suspense> component, render the product's title inside an <h2> element and its description inside a <p> element.
  6. Do not modify the existing structure or content of the #fallback template.

Expected result

Your solution should correctly use a top-level await with axios.get() to fetch product data. The <template> should then use standard text interpolation ({{ }}) to display the extracted title and description.

vue
<script setup>
import axios from 'axios';

// Using top-level await makes the entire component's setup asynchronous.
// Suspense will wait for this promise to resolve before rendering the #default slot.
const response = await axios.get('https://dummyjson.com/products/1');
const { title, description } = response.data;

</script>

<template>
  <div id="app">
    <h1>Product Display</h1>
    <Suspense>
      <!-- This template is rendered only after the `await` in setup completes -->
      <template #default>
        <div class="product-card">
          <h2>{{ title }}</h2>
          <p>{{ description }}</p>
        </div>
      </template>

      <!-- This template is rendered immediately and shown until the setup promise resolves -->
      <template #fallback>
        <div class="loading-card">
          <p>Loading product, please wait...</p>
        </div>
      </template>
    </Suspense>
  </div>
</template>
vue

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.