0
0
Astroframework~30 mins

Why data fetching happens at build time in Astro - See It in Action

Choose your learning style9 modes available
Why Data Fetching Happens at Build Time in Astro
📖 Scenario: You are building a simple Astro website that shows a list of blog post titles fetched from a data source.To make the site fast and efficient, you will fetch the data at build time, so the page is ready to serve without waiting for data on each visit.
🎯 Goal: Create an Astro component that fetches blog post data at build time and displays the titles in a list.
📋 What You'll Learn
Create a variable called posts with an array of blog post objects containing id and title.
Add a configuration variable called maxPosts to limit how many posts to show.
Use a const declaration with Astro.fetchContent() or a simulated data fetch to get posts at build time.
Render the list of post titles inside an HTML <ul> element.
💡 Why This Matters
🌍 Real World
Websites often fetch data at build time to create fast, static pages that load instantly for users.
💼 Career
Understanding build time data fetching is key for frontend developers working with modern frameworks like Astro, Next.js, or Gatsby.
Progress0 / 4 steps
1
Create the initial blog post data
Create a variable called posts with an array of three blog post objects. Each object should have an id and a title exactly as follows: { id: 1, title: 'Welcome to Astro' }, { id: 2, title: 'Building Fast Websites' }, and { id: 3, title: 'Why Build Time Data Fetching?' }.
Astro
Hint

Use const posts = [ ... ] to create the array with exact objects.

2
Add a configuration variable to limit posts
Add a variable called maxPosts and set it to 2. This will limit how many posts to show on the page.
Astro
Hint

Use const maxPosts = 2; to create the limit variable.

3
Fetch posts data at build time
Simulate fetching posts data at build time by creating a const called fetchedPosts that slices the posts array using maxPosts. Use posts.slice(0, maxPosts) to get the first two posts.
Astro
Hint

Use const fetchedPosts = posts.slice(0, maxPosts); to simulate build time data fetching.

4
Render the list of post titles
Render an unordered list <ul> in Astro that loops over fetchedPosts and displays each post's title inside a <li>. Use Astro's syntax: {fetchedPosts.map(post => <li key={post.id}>{post.title}</li>)} inside the <ul>.
Astro
Hint

Use Astro's JSX-like syntax to map over fetchedPosts and render <li> elements inside <ul>.