Build a Vue useFetch composable: refetch on a reactive URL, abort stale requests, fetch hooks and scope cleanup

hardAbout 55 minutesUpdated CodingProvuecomposablesfetchabortcontrollerrace-conditionseffect-scope
Not solved

Share this question

Problem

Data fetching is the composable every Vue interview ends up at. A naive version (watch(url, async () => { data.value = await (await fetch(url.value)).json() })) has three bugs: a slow early response overwrites a fast later one, requests keep running after the component unmounts, and errors and loading flags drift out of sync. Build a useFetch in the style of VueUse's that gets these right, using the small reactivity core in the starter.

const id = ref(1);
const { data, error, isFetching } = useFetch(() => `/api/users/${id.value}`, { fetch, refetch: true });
id.value = 2; // aborts the request for user 1; only user 2 can land in data

Ref. UR-1465 · © UIRound · uiround.com/questions/build-a-vue-usefetch-composable-refetch-on-a-reactive-url-abort-stale-requests-fetch-hooks-and-scope-cleanup

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment