0 day streak
javascript / beginner
Snippet

Fetching Remote User Profiles with Async Await in Vue

The async/await syntax allows writing asynchronous JavaScript code that reads like synchronous code. Wrapping network calls with try/catch/finally ensures that errors are caught gracefully and loading indicators in Vue components are always reset.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { ref } from 'vue';
const user = ref(null);
const isLoading = ref(false);
const errorMessage = ref('');
async function fetchUserData(userId) {
isLoading.value = true;
errorMessage.value = '';
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
user.value = await response.json();
} catch (err) {
errorMessage.value = err.message;
} finally {
isLoading.value = false;
}
}
vue
Breakdown
1
const isLoading = ref(false);
A reactive flag used by the UI to show or hide a loading spinner.
2
async function fetchUserData(userId) {
Marks the function as asynchronous to allow the use of the await keyword inside it.
3
const response = await fetch(`https://api.example.com/users/${userId}`);
Pauses function execution until the HTTP fetch request resolves.
4
if (!response.ok) {
Checks if the HTTP status is outside the successful 200-299 range and throws an error.
5
user.value = await response.json();
Parses the incoming JSON body and assigns the result to the reactive user ref.
6
finally { isLoading.value = false; }
Guarantees that the loading state is turned off regardless of whether the request succeeded or failed.