4. What is wrong with this Vue <script setup> code that tries to fetch data on mount?
import { onMounted } from 'vue';
onMounted(() => {
const response = fetch('https://api.example.com/data');
const data = response.json();
console.log(data);
});
medium
A. Missing async/await causing response and data to be Promises
B. Using onMounted instead of created hook
C. fetch URL is invalid syntax
D. console.log should be inside a separate function
Solution
Step 1: Identify async usage problem
fetch returns a Promise, so response is a Promise, not the actual response.
Step 2: Explain consequence of missing await
Calling response.json() on a Promise causes data to be a Promise too, so logging it shows a Promise object, not data.
Final Answer:
Missing async/await causing response and data to be Promises -> Option A
Quick Check:
Always await fetch and json() [OK]
Hint: Always use async/await with fetch to get real data [OK]
Common Mistakes:
Not marking onMounted callback async
Not awaiting fetch and json() calls
Expecting immediate data without Promises
5. You want to fetch user data from an API and show a loading message while waiting. Which Vue <script setup> code correctly handles loading, success, and error states for a GET request?
hard
A. import { ref, onMounted } from 'vue';
const user = ref(null);
const loading = ref(true);
const error = ref(null);
onMounted(async () => {
try {
const res = await fetch('https://api.example.com/user');
if (!res.ok) throw new Error('Fetch failed');
user.value = await res.json();
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
});