Build Vue's defineAsyncComponent: a shared loader, delayed loading state, timeout, onError retries and Suspense
Problem
defineAsyncComponent(() => import("./Chart.vue")) is how Vue apps split a heavy component into its own chunk. The wrapper it returns decides what to render while the chunk loads: nothing at first, a loading component if the wait is long enough to notice, an error component on failure or timeout, and the real component once it arrives. It also deduplicates the request and can retry. Build it.
const Chart = defineAsyncComponent({
loader: () => import("./Chart.js"),
loadingComponent: Spinner,
errorComponent: LoadFailed,
delay: 200,
timeout: 3000,
});
const render = Chart.setup({ data }, instance);
render(); // null: under 200ms the spinner would only flash
// 200ms later: { type: Spinner, props: null }; after the load: { type: ChartComponent, props: { data } }Ref. UR-1459 · © UIRound · uiround.com/questions/build-vues-defineasynccomponent-a-shared-loader-delayed-loading-state-timeout-onerror-retries-and-suspense
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
- 1Keep
pendingRequestandresolvedCompin the closure ofdefineAsyncComponent, not insetup. Every mount shares one request, and once the component is resolved a new mount renders it straight away with no loading state.
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.