How to fetch data in Vue with fetch API
Fetching data from APIs is a fundamental requirement in modern Vue applications, from loading user profiles to retrieving dynamic content. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development including Vue.js since 2014, I’ve implemented countless data-driven interfaces that require robust API integration. The most effective approach is using the fetch API within Vue 3’s Composition API with reactive state management for loading, error, and data states. This method provides excellent control over the request lifecycle while maintaining Vue’s reactivity benefits.
Use the fetch API with reactive state management in Vue’s Composition API for robust data fetching with loading and error handling.
import { ref, onMounted } from 'vue'
export default {
setup() {
const data = ref(null)
const loading = ref(false)
const error = ref(null)
const fetchData = async () => {
loading.value = true
error.value = null
try {
const response = await fetch('/api/users')
if (!response.ok) throw new Error('Failed to fetch')
data.value = await response.json()
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
}
onMounted(fetchData)
return { data, loading, error, fetchData }
}
}
This pattern uses reactive references to manage the complete data fetching lifecycle. The loading state indicates when a request is in progress, error captures any failures, and data holds the successful response. The async function handles the fetch operation with proper error handling and ensures the loading state is always updated. The onMounted hook triggers the initial data fetch when the component is ready.
Best Practice Note:
This is the approach we use in CoreUI Vue components for API integration. Consider adding request cancellation with AbortController for components that unmount during requests, and implement retry logic for production applications that need robust error recovery.



