nextjs unstable_cache sometimes doesn't return any data unexpectedly
Unanswered
Bonga shad posted this in #help-forum
Bonga shadOP
I have this method that uses
I expect every time the method is called, it should return a list of records of fixed length off 4 (either from cache, or fetching from database). However, I realized that sometimes the method doesn't return any data. It is inconsistent.
This is how I used
I tested it locally, and seeing many times it returns no data:
unstable_cache to fetch data from Vercel postgres db, and cache it for 10 seconds.I expect every time the method is called, it should return a list of records of fixed length off 4 (either from cache, or fetching from database). However, I realized that sometimes the method doesn't return any data. It is inconsistent.
This is how I used
unstable_cache, I wonder if I did something not right.export async function fetchData(geoName: string, year: number, month: string) {
try {
const data = await unstable_cache(async () => fetchDataAction(geoName, year, month), [], { revalidate: 10 });
// log to validate if data is returned properly for a given geoName.
console.log("fetched data for " + geoName + ", size: " + data.length);
return data;
} catch (error) {
console.error('Database Error:', error);
throw new Error('Failed to fetch card data.');
}
}
export async function fetchDataAction(geoName: string, year: number, month: string) {
const data = await sql<MarketTrendData>`
SELECT *
FROM my_vercel_postgres_table
WHERE geo_name=${geoName}
AND year=${year}
AND month=${month}`;
return data.rows;
}I tested it locally, and seeing many times it returns no data:
- When it's good:
GET /map/New%20Hampshire?_rsc=bjq2a 200 in 17ms
fetched data for New%20Hampshire, size: 4
- When it returns no data:
GET /map/Michigan?_rsc=hc3wf 200 in 21ms
✓ Compiled in 1739ms (2077 modules)
fetched data for Michigan, size: 0