0
0
Vueframework~30 mins

Nuxt data fetching (useFetch, useAsyncData) in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Nuxt Data Fetching with useFetch and useAsyncData
📖 Scenario: You are building a simple Nuxt 3 app that shows a list of users fetched from a public API. You want to learn how to fetch data using Nuxt's useFetch and useAsyncData composables.
🎯 Goal: Create a Nuxt 3 page component that fetches user data from https://jsonplaceholder.typicode.com/users using useFetch and useAsyncData. Display the users' names in a list.
📋 What You'll Learn
Create a Nuxt 3 page component with a template and script setup
Use useFetch to fetch user data from the API
Use useAsyncData to fetch the same user data
Display the list of user names fetched by both methods separately
Ensure the component is accessible and uses semantic HTML
💡 Why This Matters
🌍 Real World
Fetching data from APIs is a common task in web apps. Nuxt 3 provides easy ways to fetch data on the server or client side using composables like useFetch and useAsyncData.
💼 Career
Understanding Nuxt data fetching is essential for frontend developers working with Vue and Nuxt frameworks to build fast, SEO-friendly web applications.
Progress0 / 4 steps
1
Setup Nuxt page and fetch users with useFetch
Create a Nuxt 3 page component with <template> and <script setup> tags. Inside the script, use useFetch to fetch data from 'https://jsonplaceholder.typicode.com/users' and store it in a variable called fetchUsers. In the template, add an unordered list that uses fetchUsers.data to display each user's name inside a <li>.
Vue
Hint

Remember to use await with useFetch inside <script setup>.

2
Add a config variable for API URL
Add a constant variable called apiUrl and set it to 'https://jsonplaceholder.typicode.com/users'. Update the useFetch call to use this apiUrl variable instead of the string URL.
Vue
Hint

Define apiUrl before calling useFetch.

3
Fetch users with useAsyncData
Below the useFetch call, add a new constant called asyncUsers. Use useAsyncData with the key 'users' and a fetch function that fetches from apiUrl and returns the JSON response. In the template, add a new section with heading Users (useAsyncData) and an unordered list that displays each user's name from asyncUsers.data.
Vue
Hint

Use await useAsyncData('users', () => fetch(apiUrl).then(res => res.json())).

4
Add accessibility and semantic improvements
Add a main container with <main> wrapping both user sections. Add aria-label attributes to each section describing the data source. Ensure each list uses semantic <ul> and <li> tags. Confirm the headings use <h2> tags for clear structure.
Vue
Hint

Wrap the two sections inside a <main> with an aria-label describing the content.