Discover how to make your Vue apps fetch data effortlessly and update instantly!
Why Fetch API in Vue components? - Purpose & Use Cases
Imagine you want to show a list of users on your webpage. You try to get the data by writing plain JavaScript fetch calls outside your Vue component and then manually update the HTML every time new data arrives.
This manual way is tricky because you must handle loading states, errors, and update the page yourself. It's easy to forget to update the UI or cause flickering, making your app feel slow and buggy.
Using the Fetch API inside Vue components lets you load data reactively. Vue automatically updates the page when data arrives, and you can easily show loading or error messages with simple code.
fetch('https://api.example.com/users').then(res => res.json()).then(data => { document.getElementById('list').innerHTML = JSON.stringify(data) })
import { ref } from 'vue' const users = ref([]) fetch('https://api.example.com/users').then(res => res.json()).then(data => users.value = data)
You can build smooth, interactive apps that update data on the page automatically without messy manual DOM changes.
Think of a weather app that fetches the latest forecast and updates the display instantly as new data comes in, all handled cleanly inside Vue components.
Manual data fetching requires extra work to update the UI correctly.
Fetch API inside Vue components makes data loading reactive and simple.
This leads to cleaner code and better user experiences.
Practice
Solution
Step 1: Understand Fetch API role
The Fetch API is used to request data from a server or internet resource.Step 2: Connect Fetch API to Vue component
Inside Vue components, fetch is used to load data that the component will display or use.Final Answer:
To get data from the internet and use it in the component -> Option CQuick Check:
Fetch API = get data [OK]
- Thinking Fetch API styles components
- Confusing fetch with event handling
- Using fetch to create components
<script setup> component to load data on mount?Solution
Step 1: Identify lifecycle hook for data loading
onMounted() runs code after the component appears, perfect for fetching data.Step 2: Match fetch usage to lifecycle hook
Calling fetch inside onMounted() ensures data loads once component is ready.Final Answer:
Call fetch inside the onMounted() lifecycle hook -> Option AQuick Check:
Fetch in onMounted = correct usage [OK]
- Trying to fetch data in template (not allowed)
- Using computed for async fetch (wrong usage)
- Using watchEffect without dependencies causing repeated fetch
<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);
}
});Solution
Step 1: Analyze fetch and await usage
The code fetches a post from the API and waits for the JSON response.Step 2: Check console.log output
It logs the title property of the fetched post, so it prints the post's title.Final Answer:
Logs the title of the post with id 1 from the API -> Option DQuick Check:
Fetch success logs title [OK]
- Assuming fetch always fails
- Thinking async is not allowed in onMounted
- Expecting undefined because of missing await
<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');
});Solution
Step 1: Check how ref is updated
Refs in Vue must be updated by setting their .value property, not the ref variable itself.Step 2: Identify incorrect assignment
The code assigns json directly to data, which breaks reactivity; it should be data.value = json.Final Answer:
Assigning json directly to data instead of data.value -> Option AQuick Check:
Update ref with .value [OK]
- Forgetting .value when setting ref
- Confusing async/await with then chaining
- Thinking onMounted is wrong lifecycle hook here
<script setup> code correctly implements fetch with loading and error states?Solution
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.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.Final Answer:
Uses refs with onMounted, try/catch/finally for loading and error states -> Option BQuick Check:
Loading true before fetch, false after [OK]
- Not using ref for reactive state
- Setting loading false too early
- Missing error handling in async fetch
Ready to prove it?
Pass the test and this pattern moves unknown
