Move a data layer from fetch's cache options to "use cache", cacheLife, and cacheTag
Leaf and Kettle's data layer, lib/teas.ts, was written for the older caching model, where each fetch told the Data Cache how to keep its response. The app now runs with Cache Components, as create-next-app sets it up. Rewrite it so each function keeps the caching it had, with the new tools: start a cached function's body with "use cache", call cacheLife and cacheTag from next/cache inside it, and give its fetch no cache or next options.
getTeas() was kept for an hour and tagged teas: give it a lifetime whose revalidate is an hour. getTea(slug) was kept until staff revalidated teas or tea:<slug>, with no time limit: tag it the same, with a lifetime that doesn't revalidate by time for at least 30 days, like the built-in max. getStock(slug) was never cached and must still ask the warehouse on every call. Keep each URL and what each function returns, and run cacheLife once per call.
lib/teas.tsimport { cacheLife, cacheTag } from "next/cache";
const API = "https://api.leafandkettle.example";
export type Tea = { slug: string; name: string; price: number };
export async function getTeas(): Promise<Tea[]> {
const response = await fetch(`${API}/teas`, { cache: "force-cache", next: { revalidate: 3600, tags: ["teas"] } });
return response.json();
}
export async function getTea(slug: string): Promise<Tea> {
const response = await fetch(`${API}/teas/${slug}`, { cache: "force-cache", next: { tags: ["teas", `tea:${slug}`] } });
return response.json();
}
export async function getStock(slug: string): Promise<number> {
const response = await fetch(`${API}/stock/${slug}`, { cache: "no-store" });
const { tins } = (await response.json()) as { tins: number };
return tins;
}
- getTeas is a cached function, tagged teas, that revalidates after an hour
- getTea is cached under teas and its own tag, with no time-based revalidation for 30 days
- the cached reads call fetch with no cache or next options, at the same URLs
- getStock stays outside any cache and asks the warehouse each time
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…