javascript / beginner
Snippet
Handling Asynchronous API Requests on Component Mount
Managing async operations with async/await and try/catch/finally ensures clear state transitions for loading, data storage, and error indicators when components mount.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ref, onMounted } from 'vue';const userProfile = ref(null);const isLoading = ref(false);const fetchError = ref(null);onMounted(async () => {isLoading.value = true;try {const response = await fetch('https://api.example.com/profile');if (!response.ok) {throw new Error(`HTTP Error: ${response.status}`);}userProfile.value = await response.json();} catch (err) {fetchError.value = err.message;} finally {isLoading.value = false;}});
vue
Breakdown
1
const isLoading = ref(false);
Declares a boolean flag used to track whether the network request is currently active.
2
onMounted(async () => {
Registers an asynchronous lifecycle hook that executes immediately after the component is mounted.
3
const response = await fetch('https://api.example.com/profile');
Awaits the HTTP network response from the API endpoint.
4
if (!response.ok) { throw new Error(`HTTP Error: ${response.status}`); }
Checks if the HTTP response status is unsuccessful and triggers the catch block.
5
finally { isLoading.value = false; }
Guarantees that the loading indicator turns off regardless of success or failure.