Bird
Raised Fist0
Astroframework~20 mins

Caching API responses in Astro - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Astro Caching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Astro component with caching?

Consider this Astro component that fetches data and caches it for 10 seconds. What will it render if the API returns { message: 'Hello' }?

Astro
---
import { cache } from 'astro/cache';
const fetchData = async () => {
  return await cache(async () => {
    const res = await fetch('https://api.example.com/greet');
    return res.json();
  }, 10000);
};
const data = await fetchData();
---
<p>{data.message}</p>
A<p>Hello</p>
B<p>undefined</p>
C<p>{message}</p>
D<p>Error: cache is not a function</p>
Attempts:
2 left
💡 Hint

Think about what the cache function returns after fetching.

📝 Syntax
intermediate
2:00remaining
Which option correctly caches API data for 5 minutes in Astro?

Choose the correct code snippet that caches the API response for 300000 milliseconds (5 minutes) using Astro's cache function.

Aconst data = await cache(async () => await fetch('https://api.example.com/data').then(r => r.json()), 300000);
Bconst data = await cache(async () => fetch('https://api.example.com/data').json(), 300000);
Cconst data = await cache(() => fetch('https://api.example.com/data').json(), 300000);
Dconst data = cache(async () => await fetch('https://api.example.com/data').json(), 300000);
Attempts:
2 left
💡 Hint

Remember to await the fetch and parse JSON properly inside an async function.

🔧 Debug
advanced
2:00remaining
Why does this Astro cache code throw an error?

This code throws TypeError: cache is not a function. What is the cause?

---
import cache from 'astro/cache';
const data = await cache(async () => {
  const res = await fetch('https://api.example.com/info');
  return res.json();
}, 60000);
---
AThe cache function requires a third argument for options
BThe import should use curly braces: <code>import { cache } from 'astro/cache';</code>
CThe fetch URL is invalid causing the error
DThe cache function must be called without await
Attempts:
2 left
💡 Hint

Check how cache is imported from the module.

❓ state_output
advanced
2:00remaining
What is the value of data after running this Astro caching code?

Given this code snippet, what is the value of data if the API returns { count: 42 }?

---
import { cache } from 'astro/cache';
const data = await cache(async () => {
  const response = await fetch('https://api.example.com/count');
  const json = await response.json();
  return json.count * 2;
}, 15000);
---
A42
B{ count: 42 }
Cundefined
D84
Attempts:
2 left
💡 Hint

Look at what the async function returns inside the cache.

🧠 Conceptual
expert
3:00remaining
Which statement about Astro's cache function is TRUE?

Choose the correct statement about how Astro's cache function works when caching API responses.

AIt caches only the fetch request but not the parsed JSON data.
BIt caches the API response permanently until the server restarts.
CIt caches the result of the async function and reuses it until the timeout expires, then refetches on next call.
DIt caches data only on the client side, not during server rendering.
Attempts:
2 left
💡 Hint

Think about how caching with a timeout usually works in server frameworks.

Practice

(1/5)
1. What is the main benefit of caching API responses in Astro?
easy
A. It speeds up the site by reusing previously fetched data
B. It increases the size of the API response
C. It makes the API slower to respond
D. It disables the API from updating

Solution

  1. Step 1: Understand caching purpose

    Caching stores data from previous API calls to avoid fetching again.
  2. Step 2: Identify benefit in Astro context

    Reusing cached data reduces load time and speeds up the site.
  3. Final Answer:

    It speeds up the site by reusing previously fetched data -> Option A
  4. Quick Check:

    Caching = Speed up site [OK]
Hint: Caching saves time by reusing data, not slowing down [OK]
Common Mistakes:
  • Thinking caching makes API slower
  • Confusing cache with data size increase
  • Believing cache disables updates
2. Which syntax correctly sets cache revalidation time in Astro?
easy
A. const data = await fetch('https://api.example.com/data', { refresh: 60 });
B. const data = await fetch('https://api.example.com/data', { cacheTime: 60 });
C. const data = await fetch('https://api.example.com/data', { revalidate: 60 });
D. const data = await fetch('https://api.example.com/data', { updateAfter: 60 });

Solution

  1. Step 1: Recall correct property name

    The correct property to control cache duration is revalidate.
  2. Step 2: Match syntax with Astro docs

    The syntax uses { revalidate: 60 } inside fetch().
  3. Final Answer:

    const data = await fetch('https://api.example.com/data', { revalidate: 60 }); -> Option C
  4. Quick Check:

    Use revalidate property = const data = await fetch('https://api.example.com/data', { revalidate: 60 }); [OK]
Hint: Remember 'revalidate' sets cache time in seconds [OK]
Common Mistakes:
  • Using wrong property names like cacheTime or refresh
  • Forgetting to return an object
  • Placing revalidate outside return
3. Given this code snippet in Astro:
const data = await fetch('https://api.example.com/data', { revalidate: 120 }).then(res => res.json());

What happens when a user visits the page after 3 minutes?
medium
A. The cached data is used without fetching again
B. The cache is cleared but data is not fetched
C. The page shows an error due to cache expiry
D. The data is fetched again from the API

Solution

  1. Step 1: Understand revalidate timing

    The revalidate: 120 means cache lasts 120 seconds (2 minutes).
  2. Step 2: Compare visit time with cache duration

    After 3 minutes (180 seconds), cache expired, so Astro fetches fresh data.
  3. Final Answer:

    The data is fetched again from the API -> Option D
  4. Quick Check:

    Cache expired after 120s, fetch again [OK]
Hint: If visit time > revalidate, data refetches [OK]
Common Mistakes:
  • Assuming cache lasts forever
  • Thinking cache clears but no fetch happens
  • Confusing cache expiry with errors
4. Identify the error in this Astro caching code:
const data = await fetch('https://api.example.com/data').json();
medium
A. Missing await before .json() call
B. Incorrect property name 'revalidate'
C. fetch URL is invalid
D. Return statement missing props object

Solution

  1. Step 1: Check fetch usage

    fetch returns a Promise; calling .json() needs to await the fetch first.
  2. Step 2: Identify missing await

    Code calls fetch(...).json() without awaiting fetch, causing error.
  3. Final Answer:

    Missing await before .json() call -> Option A
  4. Quick Check:

    Await fetch before .json() [OK]
Hint: Always await fetch before calling .json() [OK]
Common Mistakes:
  • Calling .json() directly on fetch without await
  • Misnaming revalidate property
  • Assuming fetch URL is wrong without checking
5. You want to cache API data in Astro but update it every hour. Which is the best way to set revalidate and why?

Options:
A) revalidate: 3600 to update every hour
B) revalidate: 60 to update every minute
C) revalidate: 0 to never cache
D) revalidate: -1 to disable caching
hard
A. revalidate: 60 to update every minute
B. revalidate: 3600 to update every hour
C. revalidate: 0 to never cache
D. revalidate: -1 to disable caching

Solution

  1. Step 1: Understand revalidate meaning

    revalidate sets cache duration in seconds before refreshing data.
  2. Step 2: Match desired update frequency

    To update every hour, set revalidate to 3600 seconds (60*60).
  3. Step 3: Evaluate other options

    60 seconds updates too often, 0 disables caching, -1 is invalid.
  4. Final Answer:

    revalidate: 3600 to update every hour -> Option B
  5. Quick Check:

    1 hour = 3600 seconds revalidate [OK]
Hint: Set revalidate in seconds matching update frequency [OK]
Common Mistakes:
  • Using too short revalidate causing frequent fetches
  • Setting zero disables caching, not hourly update
  • Negative values are invalid
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard