JAVASCRIPT
Fetching Asynchronous Data in Vue 3 Components with onMounted
Discover how to efficiently fetch data from an API using the `onMounted` lifecycle hook and `async/await` syntax in Vue 3 Composition API components.
<template>
<div>
<h1>User Data</h1>
<p v-if="loading">Loading user data...</p>
<p v-else-if="error">Error: {{ error }}</p>
<div v-else-if="user">
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<p>Company: {{ user.company.name }}</p>
</div>
<p v-else>No user data available.</p>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const user = ref(null);
const loading = ref(true);
const error = ref(null);
onMounted(async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
user.value = await response.json();
} catch (err) {
error.value = err.message;
} finally {
loading.value = false;
}
});
</script>
How it works: This snippet demonstrates how to fetch asynchronous data from an API when a Vue 3 component is mounted to the DOM. It uses the `onMounted` lifecycle hook, which runs after the component has been rendered for the first time. The `async/await` syntax makes handling promises cleaner, and `ref`s (`user`, `loading`, `error`) are used to manage the data, loading state, and any errors encountered during the fetch, providing a robust UI experience.