Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How do I use the Local API with tag revalidation in Next? (3.0-beta)

default discord avatar
rezzzy12 months ago
2

I am currently fetching from my

posts

collection like this:



import { getPayload } from "payload";
import configPromise from "@payload-config";
import { Post as PostType } from "@/payload-types";
import { PaginatedDocs } from "payload/database";

export default async function Posts() {
  const payload = await getPayload({ config: configPromise });
  
  // How can this be stored with a specific cache key for use with revalidateTag?
  const data: PaginatedDocs<PostType> = await payload.find({
    collection: "posts",
  });

  return (
    // ... display the posts  
  )
}


How (if possible) can I cache this data using a cache tag?



I am aware of the

afterChange

collection hook, which I have already setup with an

/api/revalidate

route handler that will

revalidateTag

with a chosen key. I just need my data to be stored with a key I specified.



Am I overlooking something? Can I not use

revalidateTag

?



Thanks in advance!

  • default discord avatar
    Deleted User12 months ago
    https://nextjs.org/docs/app/api-reference/functions/unstable_cache

    You can try next js unstable_cache which allows giving keys to functions which can be called to revalidate from anywhere

  • default discord avatar
    rezzzy12 months ago

    Thanks for pointing me in the right direction. I was able to get this working with:



    const getPublishedPosts = unstable_cache(
      async () => {
        const payload = await getPayload({ config: configPromise });
    
        const data: PaginatedDocs<PostType> = await payload.find({
          collection: "posts",
          where: {
            _status: {
              equals: "published",
            },
          },
        });
    
        return data?.docs || [];
      },
      ["page_posts"],
      { tags: ["posts"] }
    );
    
    
    export default async function Posts() {
      const posts = await getPublishedPosts();
    
      return (
        // ... display the posts  
      )
    }
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.