Skip to content

Docs: [Cache Components] "use cache" pitfalls with map() #86896

@gaearon

Description

@gaearon

What is the documentation issue?

Here's a fix I'm going to deploy now:

 const resolveDidToHandle = cache(async function resolveDidToHandle(did: string): Promise<string> {
   "use cache: redis";
   tagDid(did);
@@ -156,7 +160,7 @@ export const resolveHandleToDid = cache(async function resolveHandleToDid(
 
 async function batchResolveHandles(dids: string[]): Promise<Map<string, string>> {
   const unique = [...new Set(dids)];
-  const results = await Promise.all(unique.map(resolveDidToHandle));
+  const results = await Promise.all(unique.map((did) => resolveDidToHandle(did)));
   return new Map(unique.map((did, i) => [did, results[i]]));
 }
 
@@ -191,8 +195,8 @@ async function batchResolveUsers(dids: string[]): Promise<Map<string, User>> {
   if (unique.length === 0) return new Map();
 
   const [handles, avatars] = await Promise.all([
-    Promise.all(unique.map(resolveDidToHandle)),
-    Promise.all(unique.map(tryFetchBskyAvatar)),
+    Promise.all(unique.map((did) => resolveDidToHandle(did))),
+    Promise.all(unique.map((did) => tryFetchBskyAvatar(did))),
   ]);

Without this fix, my Redis cache handler wasn't working properly.

Can you spot why?

Is there any context that might help us understand?

I'm honestly not sure if this is something to call out in the docs, if this could be linted against, or something else. But it was extremely confusing. (To clarify, the issue is that map sends the array and the index to the mapped function, which implicitly become cache keys, blowing up the cache size and making it miss often.)

For what it's worth, a mode that simply logs the captured cache keys would've helped here.

Does the docs page already exist? Please link to it.

https://nextjs.org/docs/app/api-reference/directives/use-cache#cache-keys

Metadata

Metadata

Assignees

No one assigned

    Labels

    Cache ComponentsRelated to the `cacheComponents`, `useCache`, or `ppr` experimental flags.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions