Bird
Raised Fist0
Vueframework~20 mins

GET requests in components in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Vue GET Requests Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Vue component display after mounting?

Consider this Vue 3 component using the Composition API. It fetches user data from an API on mount.

import { ref, onMounted } from 'vue';

export default {
  setup() {
    const user = ref(null);
    onMounted(async () => {
      const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
      user.value = await res.json();
    });
    return { user };
  }
}

What will be rendered inside the template if it shows {{ user?.name || 'Loading...' }}?

AThrows a runtime error because user is null initially
BShows 'Loading...' forever because fetch is not awaited
CDisplays the user's name after data loads, initially shows 'Loading...'
DDisplays an empty string because user.name is undefined
Attempts:
2 left
💡 Hint

Think about how ref and onMounted work together with async fetch.

📝 Syntax
intermediate
2:00remaining
Which option correctly fetches data in a Vue 3 component's setup()?

Choose the code snippet that correctly fetches JSON data and assigns it to a ref inside setup() using async/await.

A
const data = ref(null);
onMounted(async () => {
  const res = await fetch('url');
  data.value = await res.json();
});
B
const data = ref(null);
await fetch('url').then(res => res.json()).then(json => data.value = json);
C
const data = ref(null);
const res = fetch('url');
data.value = res.json();
D
const data = ref(null);
fetch('url').then(res => data = res.json());
Attempts:
2 left
💡 Hint

Remember to use onMounted for side effects and update ref.value.

🔧 Debug
advanced
2:00remaining
Why does this Vue component fail to update after fetch?

Look at this Vue 3 component snippet:

import { ref, onMounted } from 'vue';

export default {
  setup() {
    const info = ref(null);
    onMounted(() => {
      fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => {
          info = data;
        });
    });
    return { info };
  }
}

Why does the template not update with the fetched data?

ABecause the API URL is invalid and fetch fails silently
BBecause fetch is not awaited inside onMounted
CBecause onMounted should not be used for fetch calls
DBecause info is reassigned directly instead of updating info.value
Attempts:
2 left
💡 Hint

Remember how to update reactive refs in Vue.

❓ state_output
advanced
2:00remaining
What is the value of 'count' after this Vue component fetches data?

Given this Vue 3 component:

import { ref, onMounted } from 'vue';

export default {
  setup() {
    const count = ref(0);
    onMounted(async () => {
      const res = await fetch('https://jsonplaceholder.typicode.com/posts');
      const posts = await res.json();
      count.value = posts.length;
    });
    return { count };
  }
}

What will count.value be after the fetch completes?

A100
BThrows an error because posts is not an array
CUndefined
D0
Attempts:
2 left
💡 Hint

Check the API response shape at https://jsonplaceholder.typicode.com/posts.

🧠 Conceptual
expert
2:00remaining
Why use onMounted for GET requests in Vue components?

In Vue 3 Composition API, why is it best practice to place GET requests inside onMounted() instead of directly in setup()?

ABecause setup() cannot be async, so fetch must be in onMounted()
BBecause setup() runs before the component is mounted, so DOM or reactive context may not be ready for side effects
CBecause onMounted() delays the fetch until user interaction
DBecause fetch is not allowed inside setup() by Vue's rules
Attempts:
2 left
💡 Hint

Think about the component lifecycle and when side effects should run.

Practice

(1/5)
1. What is the main purpose of making a GET request inside a Vue component?
easy
A. To delete data on the server
B. To send data from the component to the server
C. To fetch data from a server to display in the component
D. To update the component's local state without server interaction

Solution

  1. Step 1: Understand GET request purpose

    A GET request is used to retrieve or fetch data from a server.
  2. Step 2: Relate to Vue component usage

    In Vue components, GET requests are used to get data to show in the UI.
  3. Final Answer:

    To fetch data from a server to display in the component -> Option C
  4. Quick Check:

    GET request = fetch data [OK]
Hint: GET requests retrieve data to show in components [OK]
Common Mistakes:
  • Confusing GET with POST (sending data)
  • Thinking GET updates local state only
  • Mixing GET with delete operations
2. Which of the following is the correct way to import and use the lifecycle hook to run code after a Vue component mounts for a GET request?
easy
A. import { mounted } from 'vue'; mounted(() => { /* fetch code */ });
B. import { onLoad } from 'vue'; onLoad(() => { /* fetch code */ });
C. import { useMounted } from 'vue'; useMounted(() => { /* fetch code */ });
D. import { onMounted } from 'vue'; onMounted(() => { /* fetch code */ });

Solution

  1. Step 1: Identify correct lifecycle hook name

    The correct Vue 3 lifecycle hook to run code after component mounts is onMounted.
  2. Step 2: Confirm import and usage syntax

    You import it from 'vue' and call it with a function: onMounted(() => { ... }).
  3. Final Answer:

    import { onMounted } from 'vue'; onMounted(() => { /* fetch code */ }); -> Option D
  4. Quick Check:

    Use onMounted for post-mount code [OK]
Hint: Use onMounted from 'vue' to run code after mount [OK]
Common Mistakes:
  • Using wrong hook names like mounted or onLoad
  • Forgetting to import onMounted
  • Calling lifecycle hooks incorrectly
3. Given this Vue <script setup> snippet, what will be logged to the console after the component mounts?
import { onMounted } from 'vue';

onMounted(async () => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  console.log(data.message);
});

Assuming the server responds with { "message": "Hello Vue" }.
medium
A. undefined
B. "Hello Vue"
C. SyntaxError
D. An empty object {}

Solution

  1. Step 1: Understand fetch and JSON parsing

    The fetch call gets the response, and response.json() parses it into an object.
  2. Step 2: Access the message property

    The parsed object has a message key with value "Hello Vue", so console.log(data.message) prints "Hello Vue".
  3. Final Answer:

    "Hello Vue" -> Option B
  4. Quick Check:

    Fetch JSON message logs "Hello Vue" [OK]
Hint: Fetch + json() returns object; access keys to log values [OK]
Common Mistakes:
  • Forgetting to await response.json()
  • Logging response instead of parsed data
  • Expecting syntax errors from correct async code
4. What is wrong with this Vue <script setup> code that tries to fetch data on mount?
import { onMounted } from 'vue';

onMounted(() => {
  const response = fetch('https://api.example.com/data');
  const data = response.json();
  console.log(data);
});
medium
A. Missing async/await causing response and data to be Promises
B. Using onMounted instead of created hook
C. fetch URL is invalid syntax
D. console.log should be inside a separate function

Solution

  1. Step 1: Identify async usage problem

    fetch returns a Promise, so response is a Promise, not the actual response.
  2. Step 2: Explain consequence of missing await

    Calling response.json() on a Promise causes data to be a Promise too, so logging it shows a Promise object, not data.
  3. Final Answer:

    Missing async/await causing response and data to be Promises -> Option A
  4. Quick Check:

    Always await fetch and json() [OK]
Hint: Always use async/await with fetch to get real data [OK]
Common Mistakes:
  • Not marking onMounted callback async
  • Not awaiting fetch and json() calls
  • Expecting immediate data without Promises
5. You want to fetch user data from an API and show a loading message while waiting. Which Vue <script setup> code correctly handles loading, success, and error states for a GET request?
hard
A. import { ref, onMounted } from 'vue'; const user = ref(null); const loading = ref(true); const error = ref(null); onMounted(async () => { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) throw new Error('Fetch failed'); user.value = await res.json(); } catch (e) { error.value = e.message; } finally { loading.value = false; } });
B. import { ref, onMounted } from 'vue'; const user = ref(null); const loading = false; const error = null; onMounted(() => { fetch('https://api.example.com/user') .then(res => res.json()) .then(data => user.value = data) .catch(e => error = e.message); loading = false; });
C. import { reactive, onMounted } from 'vue'; const state = reactive({ user: null, loading: false, error: null }); onMounted(async () => { const res = await fetch('https://api.example.com/user'); state.user = await res.json(); state.loading = false; });
D. import { ref, onMounted } from 'vue'; const user = ref(null); const loading = ref(false); const error = ref(null); onMounted(async () => { loading.value = true; const res = await fetch('https://api.example.com/user'); user.value = await res.json(); loading.value = false; });

Solution

  1. Step 1: Check reactive state setup

    import { ref, onMounted } from 'vue'; const user = ref(null); const loading = ref(true); const error = ref(null); onMounted(async () => { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) throw new Error('Fetch failed'); user.value = await res.json(); } catch (e) { error.value = e.message; } finally { loading.value = false; } }); uses ref for user, loading, and error, properly reactive for Vue.
  2. Step 2: Verify async fetch with error handling

    import { ref, onMounted } from 'vue'; const user = ref(null); const loading = ref(true); const error = ref(null); onMounted(async () => { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) throw new Error('Fetch failed'); user.value = await res.json(); } catch (e) { error.value = e.message; } finally { loading.value = false; } }); uses async/await with try/catch/finally to handle success, errors, and loading state correctly.
  3. Final Answer:

    Option A correctly manages loading, success, and error states with reactive refs and proper async handling. -> Option A
  4. Quick Check:

    Use refs + async try/catch/finally for GET with states [OK]
Hint: Use refs and try/catch/finally for loading and error states [OK]
Common Mistakes:
  • Not using reactive refs for loading and error
  • Setting loading false too early or outside async flow
  • Ignoring error handling in 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