tezvyn:

Fetch data on first render and manage loading and error states

AI-drafted, machine-checkedSource: vuejs.orgbeginner

Tests lifecycle awareness and separation of concerns. Strong answer: use mount hook (onMounted, ngOnInit, onMount), hold reactive data/loading/error states, and render conditional UI branches. Red flag: calling fetch directly in template or render function.

WHAT THIS TESTS: Whether you know where side effects belong in a component lifecycle and how to keep UI state predictable. Interviewers want to see that you do not treat rendering as an async operation and that you isolate data logic from presentation.

A GOOD ANSWER COVERS four things in order. First, the trigger: name the correct mount hook such as onMounted in Vue, ngOnInit in Angular, or onMount in Svelte. Second, state shape: define reactive variables for data, loading, and error so the template can react to each phase. Third, the fetch flow: call the API inside the hook, update loading to true, assign the response to data on success, and catch errors into the error state. Fourth, UI mapping: render a spinner or skeleton when loading is true, show the data when it arrives, and display an error message when the error state is set.

COMMON WRONG ANSWERS: Calling fetch directly in the template expression or render body, which creates a request on every render and causes an infinite loop. Using a constructor instead of a lifecycle hook for side effects. Forgetting to initialize loading state, so the UI shows a blank screen while the request is in flight. Mutating non-reactive variables and expecting the UI to update. In Vue specifically, making the setup function async without Suspense, which can return a Promise and confuse the component tree.

LIKELY FOLLOW-UPS: How would you cancel an in-flight request if the component unmounts? The answer is to use an AbortController and abort in the unmount cleanup. What if multiple components need the same data? Extract the logic into a composable in Vue, a service in Angular, or a shared store or function in Svelte. How do you avoid waterfalls? Mention parallel fetching or hoisting data requirements to a parent or route loader.

ONE CONCRETE EXAMPLE: In Vue with the Composition API, you would import ref and onMounted, create const data = ref(null), const loading = ref(true), and const error = ref(null). Inside onMounted, call the fetch, set data.value to the result, and set loading.value to false. In the template, use v-if="loading" for a spinner, v-else-if="error" for an alert, and v-else to render the list. If you reuse this pattern, extract it into a useFetch composable that returns the three states so any component can import it.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.