Next.js Discord

Discord Forum

Next.js revalidation and deduplication for Sanity

Answered
Rhinelander posted this in #help-forum
Open in Discord
RhinelanderOP
export async function getPosts(): Promise<Posts> {
  return client.fetch(
    groq`*[_type == "post"] {
    ...
  }`,
  );
}

This is my utils for fetching all the posts.
I want to have a page where I display all my posts.
import PostCard from "@/components/post-card";
import { getPosts } from "@/sanity/lib/utils";

export default async function HomePage() {
  const posts = await getPosts();

  return (
    <>
      {posts.map((post) => (
        <PostCard key={post.slug} {...post} />
      ))}
    </>
  );
}

First How do I revalidate this page? Should I just add this:
export const revalidate = 3600

Second How do I dedupplicate for page where I show single post and fetch in component and in metadata - as far as I know next.js fetch does that by itself but I don't know about sanity fetch.
Answered by James4u
import { cache } from 'react'
 
export const getItem = cache(async (id: string) => {
  const item = await db.item.findUnique({ id })
  return item
})
View full answer

13 Replies

you can use unstable_cache()
RhinelanderOP
what about react cache
that should also work if you are in app router
RhinelanderOP
2nd question is solved but first still isn't so I won't mark the solution yet
see the last example here
import { getItem } from '@/utils/get-item'
 
export const revalidate = 3600 // revalidate the data at most every hour
 
export default async function Page({
  params: { id },
}: {
  params: { id: string }
}) {
  const item = await getItem(id)
  // ...
}
RhinelanderOP
is that corrrect
and use same cachedPosts in generateMetadata
import { cache } from 'react'
 
export const getItem = cache(async (id: string) => {
  const item = await db.item.findUnique({ id })
  return item
})
Answer
this is example of cache usage from the document
RhinelanderOP
Thank you!