0
0
Astroframework~30 mins

Caching API responses in Astro - Mini Project: Build & Apply

Choose your learning style9 modes available
Caching API responses
📖 Scenario: You are building a simple Astro component that fetches user data from an API. To improve performance and reduce repeated network requests, you want to cache the API response for a short time.
🎯 Goal: Create an Astro component that fetches user data from a public API and caches the response for 10 seconds before fetching fresh data again.
📋 What You'll Learn
Create a variable to hold the API URL
Create a cache object to store the response and timestamp
Write a function to fetch data and cache it if expired
Use the cached data in the component to render user names
💡 Why This Matters
🌍 Real World
Caching API responses helps reduce network calls and speeds up web apps by reusing recent data.
💼 Career
Understanding caching is important for frontend developers to optimize performance and user experience.
Progress0 / 4 steps
1
Set up the API URL
Create a constant called apiUrl and set it to the string "https://jsonplaceholder.typicode.com/users".
Astro
Hint

Use const to declare the API URL string.

2
Create a cache object
Create a variable called cache and set it to an object with two properties: data set to null and timestamp set to 0.
Astro
Hint

Use let to create a mutable cache object.

3
Write the fetch and cache function
Write an async function called fetchUsers that checks if the cached data is older than 10 seconds (10000 milliseconds). If yes, fetch fresh data from apiUrl, update cache.data and cache.timestamp. Return cache.data.
Astro
Hint

Use Date.now() to get current time and compare with cache.timestamp.

4
Use cached data in Astro component
In the default exported async Astro component, call fetchUsers() to get user data. Return a <ul> element that maps over the users and renders each user's name inside a <li>.
Astro
Hint

Use JSX inside the returned component to render the list.