0
0
Astroframework~10 mins

Caching API responses in Astro - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to fetch data from an API and cache it using Astro's cache API.

Astro
const response = await fetch('[1]');
const data = await response.json();
Drag options to blanks, or click blank then click option'
A'https://api.example.com/data'
B'https://api.wrong.com/info'
C'/local/data.json'
D'http://invalid-url'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a local file path instead of an API URL.
Using an incorrect or invalid URL.
2fill in blank
medium

Complete the code to cache the API response for 1 hour using Astro's cache API.

Astro
const cachedData = await Astro.cache('[1]', async () => {
  const response = await fetch('https://api.example.com/data');
  return await response.json();
}, { ttl: 3600 });
Drag options to blanks, or click blank then click option'
A'apiResponse'
B'cacheKey'
C'dataKey'
D'userData'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an empty string or non-descriptive key.
Using a key that conflicts with other cached data.
3fill in blank
hard

Fix the error in the code to correctly cache the API response with a 30-minute expiration.

Astro
const data = await Astro.cache('apiData', async () => {
  const response = await fetch('https://api.example.com/data');
  return await response.json();
}, { ttl: [1] });
Drag options to blanks, or click blank then click option'
A1800
B3600
C300
D60
Attempts:
3 left
💡 Hint
Common Mistakes
Using ttl in minutes instead of seconds.
Using a ttl value too short or too long for the requirement.
4fill in blank
hard

Fill both blanks to create a cache key using the API endpoint and user ID.

Astro
const cacheKey = '[1]' + '_' + [2];
const data = await Astro.cache(cacheKey, async () => {
  const response = await fetch('https://api.example.com/data');
  return await response.json();
}, { ttl: 600 });
Drag options to blanks, or click blank then click option'
A'apiData'
BuserId
C'cacheKey'
Duser.id
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for user ID.
Not concatenating the key parts properly.
5fill in blank
hard

Fill all three blanks to fetch, cache, and handle errors gracefully.

Astro
try {
  const data = await Astro.cache([1], async () => {
    const response = await fetch([2]);
    if (!response.ok) throw new Error('Network error');
    return await response.json();
  }, { ttl: [3] });
} catch (error) {
  console.error(error);
}
Drag options to blanks, or click blank then click option'
A'userCache'
B'https://api.example.com/user'
C300
D'cacheKey'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string for cache key.
Using an incorrect API URL.
Setting ttl to an invalid value.