javascript / intermediate
Snippet
Async State Management in Composables
Managing asynchronous requests inside a composable allows you to keep your components clean while handling loading and error states reactively across your entire application.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref } from 'vue';export function useFetch(url) {const data = ref(null);const error = ref(null);const doFetch = async () => {try {const res = await fetch(url);data.value = await res.json();} catch (err) {error.value = err;}};doFetch();return { data, error };}
vue
Breakdown
1
const data = ref(null);
Create a reactive holder for the eventual API response.
2
try { ... } catch (err) { ... }
Standard JavaScript error handling applied to reactive state updates.