Bird
Raised Fist0
Vueframework~30 mins

Fetch API in Vue components - Mini Project: Build & Apply

Choose your learning style10 modes available
Fetch API in Vue components
📖 Scenario: You are building a simple Vue 3 app that shows a list of users fetched from an online API. This is a common task when you want to display live data from a server.
🎯 Goal: Build a Vue 3 component using the Composition API that fetches user data from https://jsonplaceholder.typicode.com/users and displays their names in a list.
📋 What You'll Learn
Use the fetch API to get data
Use Vue 3 Composition API with <script setup>
Store the fetched data in a ref
Display the user names in an unordered list
Handle loading state with a simple message
💡 Why This Matters
🌍 Real World
Fetching data from APIs is essential for dynamic web apps that show live or updated information like user profiles, posts, or products.
💼 Career
Understanding how to fetch data and display it in Vue components is a key skill for frontend developers working with modern web applications.
Progress0 / 4 steps
1
Setup Vue component and data storage
Create a Vue 3 component with <script setup>. Inside it, create a ref called users and initialize it as an empty array.
Vue
Hint

Use import { ref } from 'vue' and then const users = ref([]) to create reactive data.

2
Add loading state variable
Add a ref called loading and set it to true. This will track if data is still loading.
Vue
Hint

Use const loading = ref(true) to track loading status.

3
Fetch user data using fetch API
Inside <script setup>, use fetch to get data from https://jsonplaceholder.typicode.com/users. When the data is received, set users.value to the JSON response and set loading.value to false. Use async and await inside a function called loadUsers and call it immediately.
Vue
Hint

Use async function loadUsers() with await fetch(...). Update users.value and loading.value. Call loadUsers() right after.

4
Display loading message and user list
In the <template>, add a <div> that shows Loading users... when loading is true. Otherwise, show an unordered list <ul> with each user's name inside a <li>. Use v-if and v-for directives with the exact variable names loading and users.
Vue
Hint

Use v-if="loading" to show loading text. Use v-else to show <ul>. Inside <ul>, use v-for="user in users" with :key="user.id" and display {{ user.name }}.

Practice

(1/5)
1. What is the main purpose of using the Fetch API inside a Vue component?
easy
A. To handle user input events like clicks
B. To style the component with CSS
C. To get data from the internet and use it in the component
D. To create new Vue components dynamically

Solution

  1. Step 1: Understand Fetch API role

    The Fetch API is used to request data from a server or internet resource.
  2. Step 2: Connect Fetch API to Vue component

    Inside Vue components, fetch is used to load data that the component will display or use.
  3. Final Answer:

    To get data from the internet and use it in the component -> Option C
  4. Quick Check:

    Fetch API = get data [OK]
Hint: Fetch API fetches data from internet for Vue components [OK]
Common Mistakes:
  • Thinking Fetch API styles components
  • Confusing fetch with event handling
  • Using fetch to create components
2. Which is the correct way to use fetch inside a Vue 3 <script setup> component to load data on mount?
easy
A. Call fetch inside the onMounted() lifecycle hook
B. Call fetch inside a computed property
C. Use fetch directly in the template section
D. Use fetch inside a watchEffect without dependencies

Solution

  1. Step 1: Identify lifecycle hook for data loading

    onMounted() runs code after the component appears, perfect for fetching data.
  2. Step 2: Match fetch usage to lifecycle hook

    Calling fetch inside onMounted() ensures data loads once component is ready.
  3. Final Answer:

    Call fetch inside the onMounted() lifecycle hook -> Option A
  4. Quick Check:

    Fetch in onMounted = correct usage [OK]
Hint: Use onMounted() to fetch data after component loads [OK]
Common Mistakes:
  • Trying to fetch data in template (not allowed)
  • Using computed for async fetch (wrong usage)
  • Using watchEffect without dependencies causing repeated fetch
3. What will be the output in the console when this Vue 3 <script setup> code runs?
import { ref, onMounted } from 'vue';
const data = ref(null);
const error = ref(null);
onMounted(async () => {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    data.value = await res.json();
    console.log(data.value.title);
  } catch (e) {
    error.value = 'Failed to load';
    console.log(error.value);
  }
});
medium
A. Logs undefined because data.value is never set
B. Logs 'Failed to load' always
C. Throws a syntax error because async is not allowed
D. Logs the title of the post with id 1 from the API

Solution

  1. Step 1: Analyze fetch and await usage

    The code fetches a post from the API and waits for the JSON response.
  2. Step 2: Check console.log output

    It logs the title property of the fetched post, so it prints the post's title.
  3. Final Answer:

    Logs the title of the post with id 1 from the API -> Option D
  4. Quick Check:

    Fetch success logs title [OK]
Hint: Await fetch then log data property for output [OK]
Common Mistakes:
  • Assuming fetch always fails
  • Thinking async is not allowed in onMounted
  • Expecting undefined because of missing await
4. Identify the error in this Vue 3 <script setup> snippet that fetches data:
import { ref, onMounted } from 'vue';
const data = ref(null);
const error = ref(null);
onMounted(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(json => data = json)
    .catch(() => error.value = 'Error fetching');
});
medium
A. Assigning json directly to data instead of data.value
B. Missing await keyword before fetch
C. Using onMounted instead of created lifecycle hook
D. Not returning the fetch promise

Solution

  1. Step 1: Check how ref is updated

    Refs in Vue must be updated by setting their .value property, not the ref variable itself.
  2. Step 2: Identify incorrect assignment

    The code assigns json directly to data, which breaks reactivity; it should be data.value = json.
  3. Final Answer:

    Assigning json directly to data instead of data.value -> Option A
  4. Quick Check:

    Update ref with .value [OK]
Hint: Update ref variables with .value, not direct assignment [OK]
Common Mistakes:
  • Forgetting .value when setting ref
  • Confusing async/await with then chaining
  • Thinking onMounted is wrong lifecycle hook here
5. You want to fetch user data and show a loading message while waiting. Which Vue 3 <script setup> code correctly implements fetch with loading and error states?
hard
A. const loading = false; const error = null; const user = null; onMounted(() => { fetch('/user') .then(res => res.json()) .then(data => user = data) .catch(() => error = 'Failed'); loading = false; });
B. const loading = ref(false); const error = ref(null); const user = ref(null); onMounted(async () => { loading.value = true; try { const res = await fetch('/user'); user.value = await res.json(); } catch { error.value = 'Failed to load user'; } finally { loading.value = false; } });
C. const loading = ref(true); const error = ref(''); const user = ref({}); fetch('/user').then(res => res.json()).then(data => { user.value = data; loading.value = false; }).catch(() => { error.value = 'Error'; loading.value = false; });
D. const loading = ref(false); const error = ref(null); const user = ref(null); async function loadUser() { loading.value = true; const res = await fetch('/user'); user.value = await res.json(); loading.value = false; } onMounted(loadUser);

Solution

  1. Step 1: Check reactive state setup

    const loading = ref(false); const error = ref(null); const user = ref(null); onMounted(async () => { loading.value = true; try { const res = await fetch('/user'); user.value = await res.json(); } catch { error.value = 'Failed to load user'; } finally { loading.value = false; } }); uses ref() for loading, error, and user, enabling reactivity and UI updates.
  2. Step 2: Verify fetch with loading and error handling

    It sets loading true before fetch, uses try/catch for errors, and sets loading false in finally block.
  3. Final Answer:

    Uses refs with onMounted, try/catch/finally for loading and error states -> Option B
  4. Quick Check:

    Loading true before fetch, false after [OK]
Hint: Use ref and try/catch with finally to manage loading state [OK]
Common Mistakes:
  • Not using ref for reactive state
  • Setting loading false too early
  • Missing error handling in async fetch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard