Bird
Raised Fist0
Vueframework~10 mins

Fetch API in Vue components - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Fetch API in Vue components
Component Mounted
↓
Call fetch()
↓
Send HTTP Request
↓
Wait for Response
↓
Receive Response
↓
Parse JSON Data
↓
Update Component State
↓
Re-render Component with Data
When the Vue component mounts, it calls fetch to get data from a server, waits for the response, parses it, updates the component's state, and then re-renders to show the new data.
Execution Sample
Vue
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const data = ref(null);
    onMounted(async () => {
      const res = await fetch('https://api.example.com/data');
      data.value = await res.json();
    });
    return { data };
  }
}
This Vue component fetches JSON data from an API when it mounts and stores it in a reactive variable.
Execution Table
StepActionFetch Promise StateResponse DataComponent State (data.value)Component Render
1Component mounts, onMounted runspendingnonenullShows loading or empty state
2fetch() sends HTTP requestpendingnonenullStill loading
3Response receivedfulfilled{"name":"Vue"}nullStill loading, waiting for JSON parse
4Parse JSON with res.json()fulfilled{"name":"Vue"}nullStill loading
5Assign parsed JSON to data.valuefulfilled{"name":"Vue"}{"name":"Vue"}Triggers re-render
6Component re-renders with new datafulfilled{"name":"Vue"}{"name":"Vue"}Shows data on screen
7No more updatesfulfilled{"name":"Vue"}{"name":"Vue"}Stable display
💡 Fetch completes and data.value is set, component stops updating until next change.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5Final
data.valuenullnullnull{"name":"Vue"}{"name":"Vue"}
fetch Promisenot startedpendingfulfilledfulfilledfulfilled
Key Moments - 3 Insights
Why is data.value null even after the fetch request is sent?
Because fetch is asynchronous, data.value stays null until the response is received and parsed (see execution_table steps 2-4).
What triggers the component to re-render with new data?
Assigning the parsed JSON to data.value updates the reactive variable, which triggers Vue to re-render (see execution_table step 5).
Why do we use onMounted for fetch instead of calling fetch directly in setup?
onMounted ensures the fetch runs after the component is mounted, avoiding issues with server-side rendering or premature calls.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of data.value at Step 3?
Anull
B{"name":"Vue"}
Cpending
Dundefined
💡 Hint
Check the 'Component State (data.value)' column at Step 3 in the execution_table.
At which step does the component re-render with the fetched data?
AStep 2
BStep 4
CStep 5
DStep 7
💡 Hint
Look for the step where 'Component Render' mentions 'Triggers re-render'.
If the fetch URL was incorrect and failed, what would change in the execution table?
AFetch Promise would stay pending forever
BResponse Data would be empty and data.value would remain null
CComponent would re-render with error data automatically
Ddata.value would be set to an empty object
💡 Hint
Consider what happens when fetch fails and no JSON is assigned to data.value.
Concept Snapshot
Fetch API in Vue Components:
- Use onMounted() to run fetch after component mounts
- fetch() returns a promise; await response and parse JSON
- Store data in a reactive ref variable
- Updating ref triggers component re-render
- Handle loading and errors for good UX
Full Transcript
This visual trace shows how a Vue component uses the Fetch API to get data. When the component mounts, it calls fetch to send an HTTP request. The fetch promise is pending while waiting for the server response. Once the response arrives, the component parses the JSON data and assigns it to a reactive variable called data.value. This assignment triggers Vue to re-render the component, showing the new data on screen. The variable tracker shows data.value starts as null and updates only after the fetch completes. Key moments clarify why data.value is null before the fetch finishes and what triggers the re-render. The quiz tests understanding of data state at different steps and what happens if fetch fails.

Practice

(1/5)
1. What is the main purpose of using the Fetch API inside a Vue component?
easy
A. To handle user input events like clicks
B. To style the component with CSS
C. To get data from the internet and use it in the component
D. To create new Vue components dynamically

Solution

  1. Step 1: Understand Fetch API role

    The Fetch API is used to request data from a server or internet resource.
  2. Step 2: Connect Fetch API to Vue component

    Inside Vue components, fetch is used to load data that the component will display or use.
  3. Final Answer:

    To get data from the internet and use it in the component -> Option C
  4. Quick Check:

    Fetch API = get data [OK]
Hint: Fetch API fetches data from internet for Vue components [OK]
Common Mistakes:
  • Thinking Fetch API styles components
  • Confusing fetch with event handling
  • Using fetch to create components
2. Which is the correct way to use fetch inside a Vue 3 <script setup> component to load data on mount?
easy
A. Call fetch inside the onMounted() lifecycle hook
B. Call fetch inside a computed property
C. Use fetch directly in the template section
D. Use fetch inside a watchEffect without dependencies

Solution

  1. Step 1: Identify lifecycle hook for data loading

    onMounted() runs code after the component appears, perfect for fetching data.
  2. Step 2: Match fetch usage to lifecycle hook

    Calling fetch inside onMounted() ensures data loads once component is ready.
  3. Final Answer:

    Call fetch inside the onMounted() lifecycle hook -> Option A
  4. Quick Check:

    Fetch in onMounted = correct usage [OK]
Hint: Use onMounted() to fetch data after component loads [OK]
Common Mistakes:
  • Trying to fetch data in template (not allowed)
  • Using computed for async fetch (wrong usage)
  • Using watchEffect without dependencies causing repeated fetch
3. What will be the output in the console when this Vue 3 <script setup> code runs?
import { ref, onMounted } from 'vue';
const data = ref(null);
const error = ref(null);
onMounted(async () => {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    data.value = await res.json();
    console.log(data.value.title);
  } catch (e) {
    error.value = 'Failed to load';
    console.log(error.value);
  }
});
medium
A. Logs undefined because data.value is never set
B. Logs 'Failed to load' always
C. Throws a syntax error because async is not allowed
D. Logs the title of the post with id 1 from the API

Solution

  1. Step 1: Analyze fetch and await usage

    The code fetches a post from the API and waits for the JSON response.
  2. Step 2: Check console.log output

    It logs the title property of the fetched post, so it prints the post's title.
  3. Final Answer:

    Logs the title of the post with id 1 from the API -> Option D
  4. Quick Check:

    Fetch success logs title [OK]
Hint: Await fetch then log data property for output [OK]
Common Mistakes:
  • Assuming fetch always fails
  • Thinking async is not allowed in onMounted
  • Expecting undefined because of missing await
4. Identify the error in this Vue 3 <script setup> snippet that fetches data:
import { ref, onMounted } from 'vue';
const data = ref(null);
const error = ref(null);
onMounted(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(json => data = json)
    .catch(() => error.value = 'Error fetching');
});
medium
A. Assigning json directly to data instead of data.value
B. Missing await keyword before fetch
C. Using onMounted instead of created lifecycle hook
D. Not returning the fetch promise

Solution

  1. Step 1: Check how ref is updated

    Refs in Vue must be updated by setting their .value property, not the ref variable itself.
  2. Step 2: Identify incorrect assignment

    The code assigns json directly to data, which breaks reactivity; it should be data.value = json.
  3. Final Answer:

    Assigning json directly to data instead of data.value -> Option A
  4. Quick Check:

    Update ref with .value [OK]
Hint: Update ref variables with .value, not direct assignment [OK]
Common Mistakes:
  • Forgetting .value when setting ref
  • Confusing async/await with then chaining
  • Thinking onMounted is wrong lifecycle hook here
5. You want to fetch user data and show a loading message while waiting. Which Vue 3 <script setup> code correctly implements fetch with loading and error states?
hard
A. const loading = false; const error = null; const user = null; onMounted(() => { fetch('/user') .then(res => res.json()) .then(data => user = data) .catch(() => error = 'Failed'); loading = false; });
B. const loading = ref(false); const error = ref(null); const user = ref(null); onMounted(async () => { loading.value = true; try { const res = await fetch('/user'); user.value = await res.json(); } catch { error.value = 'Failed to load user'; } finally { loading.value = false; } });
C. const loading = ref(true); const error = ref(''); const user = ref({}); fetch('/user').then(res => res.json()).then(data => { user.value = data; loading.value = false; }).catch(() => { error.value = 'Error'; loading.value = false; });
D. const loading = ref(false); const error = ref(null); const user = ref(null); async function loadUser() { loading.value = true; const res = await fetch('/user'); user.value = await res.json(); loading.value = false; } onMounted(loadUser);

Solution

  1. Step 1: Check reactive state setup

    const loading = ref(false); const error = ref(null); const user = ref(null); onMounted(async () => { loading.value = true; try { const res = await fetch('/user'); user.value = await res.json(); } catch { error.value = 'Failed to load user'; } finally { loading.value = false; } }); uses ref() for loading, error, and user, enabling reactivity and UI updates.
  2. Step 2: Verify fetch with loading and error handling

    It sets loading true before fetch, uses try/catch for errors, and sets loading false in finally block.
  3. Final Answer:

    Uses refs with onMounted, try/catch/finally for loading and error states -> Option B
  4. Quick Check:

    Loading true before fetch, false after [OK]
Hint: Use ref and try/catch with finally to manage loading state [OK]
Common Mistakes:
  • Not using ref for reactive state
  • Setting loading false too early
  • Missing error handling in async fetch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard