Question presented to candidate: "A product page loads the product for the id in the URL. Users click quickly between products and sometimes see the wrong one, and a 404 shows an empty page with no message. Show how you would fetch data in a Vue component, with loading and error states and proper cancellation."
What a strong answer should cover:
- Three pieces of state:
data,loading,error, rendered withv-if/v-else-ifso every state has a UI. - Start fetching in
setup(or awatchwithimmediate: trueon the input), not only inonMounted, and re-fetch when the input (route param, prop) changes. - Race conditions: an older, slower response can arrive last and overwrite the newer one. Cancel it with an
AbortControllerregistered viaonWatcherCleanup(Vue 3.5+) or the watcher'sonCleanupargument; ignoreAbortError. fetchonly rejects on network failure: checkres.okand throw for 4xx/5xx yourself.- Extract a composable (
useFetch) or use a data-fetching library for caching and dedupe; mention Suspense/async setup and SSR (NuxtuseFetch) as alternatives.
Clarifying questions expected:
- "Should switching products keep showing the old one while the new one loads, or show a spinner?"
- "Is this page server-rendered?"
Code / implementation expected: Yes β a component (or composable) with loading/error state and an aborted stale request.