Build a Vue useFetch composable: refetch on a reactive URL, abort stale requests, fetch hooks and scope cleanup
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 dataRef. UR-1465 · © UIRound · uiround.com/questions/build-a-vue-usefetch-composable-refetch-on-a-reactive-url-abort-stale-requests-fetch-hooks-and-scope-cleanup
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 4
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Give every
execute()a number from a counter, and after everyawaitcheck that it is still the latest one. A request that is no longer the latest must not write any state, whether it was aborted or the server simply answered late.
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.