0
0
Vueframework~30 mins

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

Choose your learning style9 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
Need a 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
Need a 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
Need a 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
Need a 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 }}.