Consider this Astro component that fetches data and caches it for 10 seconds. What will it render if the API returns { message: 'Hello' }?
--- 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>
Think about what the cache function returns after fetching.
The cache function stores the API response and returns the JSON data. The component renders the message property, so it outputs Hello.
Choose the correct code snippet that caches the API response for 300000 milliseconds (5 minutes) using Astro's cache function.
Remember to await the fetch and parse JSON properly inside an async function.
Option A correctly awaits the fetch and JSON parsing inside an async function passed to cache. Other options either miss await or call json() incorrectly.
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);
---Check how cache is imported from the module.
The cache function is a named export, so it must be imported with curly braces. Importing as default causes cache to be undefined, leading to the error.
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);
---Look at what the async function returns inside the cache.
The async function returns json.count * 2, which is 42 * 2 = 84. So data is 84.
cache function is TRUE?Choose the correct statement about how Astro's cache function works when caching API responses.
Think about how caching with a timeout usually works in server frameworks.
Astro's cache stores the async function's result and returns it for the timeout duration. After timeout, it runs the function again to refresh the cache.