Consider this Vue 3 component using the Composition API. It fetches user data from an API on mount.
import { ref, onMounted } from 'vue';
export default {
setup() {
const user = ref(null);
onMounted(async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
user.value = await res.json();
});
return { user };
}
}What will be rendered inside the template if it shows {{ user?.name || 'Loading...' }}?
Think about how ref and onMounted work together with async fetch.
The component uses ref to hold user data and fetches it on mount asynchronously. Initially, user.value is null, so the template shows 'Loading...'. After fetch completes, user.value is set to the user object, so user?.name shows the user's name.
Choose the code snippet that correctly fetches JSON data and assigns it to a ref inside setup() using async/await.
Remember to use onMounted for side effects and update ref.value.
Option A correctly uses onMounted to run the async fetch after component mounts, awaits the response, and assigns the parsed JSON to data.value. Other options either misuse await, don't await properly, or assign to the ref variable instead of its .value.
Look at this Vue 3 component snippet:
import { ref, onMounted } from 'vue';
export default {
setup() {
const info = ref(null);
onMounted(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
info = data;
});
});
return { info };
}
}Why does the template not update with the fetched data?
Remember how to update reactive refs in Vue.
The problem is that info is a ref, so to update its value reactively, you must assign to info.value. Assigning directly to info just changes the local variable and does not trigger reactivity.
Given this Vue 3 component:
import { ref, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
onMounted(async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
count.value = posts.length;
});
return { count };
}
}What will count.value be after the fetch completes?
Check the API response shape at https://jsonplaceholder.typicode.com/posts.
The API returns an array of 100 posts. So posts.length is 100, which is assigned to count.value. Initially, count is 0 but updates after fetch.
In Vue 3 Composition API, why is it best practice to place GET requests inside onMounted() instead of directly in setup()?
Think about the component lifecycle and when side effects should run.
Setup() runs synchronously before the component is mounted. Side effects like fetch calls that depend on the component being ready should be placed in onMounted(), which runs after mounting. This ensures reactive context and DOM are ready.