How to cache a DB query in Next JS 14
Answered
Eyebrowed Thrush posted this in #help-forum
Eyebrowed ThrushOP
import { prisma } from "~/lib/prisma";
export default async function Page() {
const posts = await prisma.posts.findMany();
return <div>{posts.map........?.name}</div>;
}
how I can create cache in this. I mean user refreshes I doesn't want to make request to the db
I want it something like revalidation that we use in the fetch api in next js
The code is taken from the next js official website
In my case I am using this thing to fetch /show posts
export default async function Page() {
const posts = await prisma.posts.findMany();
return <div>{posts.map........?.name}</div>;
}
how I can create cache in this. I mean user refreshes I doesn't want to make request to the db
I want it something like revalidation that we use in the fetch api in next js
The code is taken from the next js official website
In my case I am using this thing to fetch /show posts
Answered by joulev
use
unstable_cache https://nextjs.org/docs/app/api-reference/functions/unstable_cache2 Replies
@Eyebrowed Thrush import { prisma } from "~/lib/prisma";
export default async function Page() {
const posts = await prisma.posts.findMany();
return <div>{posts.map........?.name}</div>;
}
how I can create cache in this. I mean user refreshes I doesn't want to make request to the db
I want it something like revalidation that we use in the fetch api in next js
The code is taken from the next js official website
In my case I am using this thing to fetch /show posts
use
unstable_cache https://nextjs.org/docs/app/api-reference/functions/unstable_cacheAnswer
or
export const revalidate = <number>: https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#revalidate