Bird
Raised Fist0
Vueframework~10 mins

Fetch API in Vue components - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to fetch data when the component is mounted.

Vue
<script setup>
import { ref, onMounted } from 'vue'
const data = ref(null)
onMounted(() => {
  fetch([1])
    .then(response => response.json())
    .then(json => data.value = json)
})
</script>
Drag options to blanks, or click blank then click option'
A'/api/items'
B'/api/info'
C'/api/data'
D'/api/users'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the URL in quotes.
Using an incorrect or unrelated URL.
2fill in blank
medium

Complete the code to handle errors in the fetch call.

Vue
<script setup>
import { ref, onMounted } from 'vue'
const error = ref(null)
onMounted(() => {
  fetch('/api/data')
    .then(response => {
      if (!response.ok) throw new Error('Network error')
      return response.json()
    })
    .catch([1] => error.value = [1].message)
})
</script>
Drag options to blanks, or click blank then click option'
Ae
Berror
Cerr
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not declared in the catch block.
Trying to access error.message without a parameter.
3fill in blank
hard

Fix the error in the fetch call to correctly update the reactive data.

Vue
<script setup>
import { ref, onMounted } from 'vue'
const items = ref([])
onMounted(async () => {
  const response = await fetch('/api/items')
  const json = await response.json()
  items[1] = json
})
</script>
Drag options to blanks, or click blank then click option'
A.value
B[0]
C[]
D()
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning directly to the ref variable without '.value'.
Using array or function syntax incorrectly.
4fill in blank
hard

Fill both blanks to create a reactive loading state during the fetch.

Vue
<script setup>
import { ref, onMounted } from 'vue'
const loading = ref(true)
const data = ref(null)
onMounted(async () => {
  try {
    const response = await fetch('/api/data')
    data.value = await response.json()
  } finally {
    loading[1] = [2]
  }
})
</script>
Drag options to blanks, or click blank then click option'
A.value
Bfalse
Ctrue
Dloading
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use '.value' when updating refs.
Setting loading to true instead of false after fetch.
5fill in blank
hard

Fill all three blanks to fetch data and display an error message if fetch fails.

Vue
<script setup>
import { ref, onMounted } from 'vue'
const data = ref(null)
const error = ref(null)
onMounted(async () => {
  try {
    const response = await fetch([1])
    if (!response.ok) throw new Error('Fetch failed')
    data.value = await response.json()
  } catch ([2]) {
    error.value = [3].message
  }
})
</script>
Drag options to blanks, or click blank then click option'
A'/api/info'
Berr
Ce
D'/api/data'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong URL string in fetch.
Using a different variable name in catch block than in error assignment.

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