Consider this Astro component that fetches a list of users from an API in the frontmatter and renders their names:
---
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
---
-
{users.map(user =>
- {user.name} )}
What will this component render?
--- const response = await fetch('https://jsonplaceholder.typicode.com/users'); const users = await response.json(); --- <ul> {users.map(user => <li>{user.name}</li>)} </ul>
Think about what the API returns and how the map function transforms it.
The API returns an array of user objects. The map function creates a list item for each user's name, so the component renders a list of all user names.
Choose the correct Astro frontmatter code snippet that fetches data from an API and handles fetch errors gracefully.
Remember to await fetch and check response.ok to catch HTTP errors.
Option A uses try-catch to handle errors and checks if the response is OK before parsing JSON. Other options miss await or error handling.
Analyze this Astro frontmatter code snippet:
---
const response = fetch('https://api.example.com/data');
const data = await response.json();
---What error will occur when this component runs?
--- const response = fetch('https://api.example.com/data'); const data = await response.json(); ---
Consider what fetch returns if you don't await it.
fetch returns a Promise. Without awaiting fetch, response is a Promise, which does not have a json() method. So calling response.json() causes a TypeError.
Given this Astro frontmatter code:
---
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
---What is the value of data?
--- const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const data = await response.json(); ---
Check the API endpoint and what it returns.
The API returns a JSON object representing post with id 1. So data contains that object with userId, id, title, and body fields.
Choose the best explanation for why fetching API data in Astro frontmatter is often preferred over fetching it on the client side.
Think about when frontmatter code runs and how it affects the HTML sent to the browser.
Fetching in frontmatter runs on the server or build time, so the HTML sent to the browser already contains the data. This improves load speed and SEO. Client-side fetching happens after page load, which can delay content display.