Performance: Composable for API calls (useFetch pattern)
This pattern affects page load speed and interaction responsiveness by managing when and how API data is fetched and rendered.
import { ref } from 'vue'; export function useFetchUser() { const user = ref(null); const loading = ref(false); const error = ref(null); async function fetchUser() { loading.value = true; try { const res = await fetch('https://api.example.com/user'); user.value = await res.json(); } catch (e) { error.value = e; } finally { loading.value = false; } } return { user, loading, error, fetchUser }; } // Components import and reuse this composable
export default { data() { return { user: null }; }, async mounted() { const res = await fetch('https://api.example.com/user'); this.user = await res.json(); } }; // Repeated in every component needing user data
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Independent fetch in each component | Multiple redundant DOM updates | Multiple reflows per fetch | High paint cost due to repeated updates | [X] Bad |
| Composable useFetch pattern with shared state | Single DOM update per data change | Single reflow per data update | Lower paint cost with minimal updates | [OK] Good |
useFetch in Vue?useFetch composable specifically handles API calls and manages reactive states like loading and error.useFetch composable in a Vue component?useFetch(url) returns reactive properties like data and error.useFetch composable usage:const { data, loading, error } = useFetch('https://api.example.com/items');loading.value be immediately after calling useFetch?useFetch composable snippet?export function useFetch(url) {
const data = ref(null);
const loading = ref(false);
const error = ref(null);
fetch(url)
.then(res => res.json())
.then(json => { data.value = json; loading.value = false; })
.catch(err => { error.value = err; loading.value = false; });
loading.value = true;
return { data, loading, error };
}useFetch composable that automatically retries fetching up to 3 times if the API call fails. Which approach correctly adds this retry logic?Pass the test and this pattern moves unknown