Next.js Discord

Discord Forum

How do you pass dynamic tags to unstable_cache?

Answered
Chub mackerel posted this in #help-forum
Open in Discord
Chub mackerelOP
const _getLibraryByKey = 
  unstable_cache(async (libraryKey: string) => {
    const col = await getDbCollection<Library>('libraries');
    return await col.findOne({ key: libraryKey });
  }, [`library-${libraryKey}`]);

const _getItemsByAttribute = 
  unstable_cache(async (libraryKey: string, attribute: string) => {
    const col = await getDbCollection<LibraryItem>('library-items');
    return await col.find({ 'library.key': libraryKey, attribute }).toArray();
  }, [`library-${libraryKey}`]);


My goal is to use a group key to flush the cache when related items are updated.
Answered by ᴉuɐpɹɐɐ
import "server-only"
import { unstable_cache } from "next/cache"

export const getArticleComments = (id: number) =>
  unstable_cache(
    async (id: number) => {...},
    [],
    { tags: [`article-comments`, `article-comments:${id}`] }
  )(id);

then
"use server";
...
revalidateTag("article-comments");
// this will revalidate all cache that has the "article-comments" tag
View full answer

3 Replies

Answer
Chub mackerelOP
Thanks