Next.js Discord

Discord Forum

Correct way to cache data that being selected from db?

Answered
Common paper wasp posted this in #help-forum
Open in Discord
Common paper waspOP
So in a page, I have this code:
import { fetchLatest } from "@/lib/fetch-prices";
import { db } from "@/db";
import { posts} from "@/db/schema";
import { readSession } from "@/lib/session";
import { eq } from "drizzle-orm";
import PortfolioAssets from "./assets";

export default async function PortfolioPage() {
  const changingData = await fetchLatest();
  const session = await readSession();

  if (!session) {
    throw new Error("Session not found");
  }

  const myPosts = await db
    .select()
    .from(posts)
    .where(eq(posts.userId, session.userId));

  if (!prices) {
    throw new Error("Could not load prices");
  }

  return <ShowData data={myPosts} changingData={changingData} />;
}

So in this page, we have 2 data. One should always be fetched and not be cached changingData. And one should be cached until it is revalidated by some server action myPosts
What is the correct way of doing this?
Answered by B33fb0n3
yes. If you don't want that, put a user id for example also into the cache tag
View full answer

5 Replies

@B33fb0n3 you wrap the myPosts (that should be cached) inside a unstable_cache and give it a tag. This tag can then be revalidated. You can leave the rest as it is
Common paper waspOP
So let say we have 2 users.
If 1 user revalidates the "my-posts" tag, does the other user's cache also get invalidated?
@Common paper wasp So let say we have 2 users. If 1 user revalidates the "my-posts" tag, does the other user's cache also get invalidated?
yes. If you don't want that, put a user id for example also into the cache tag
Answer
Common paper waspOP
Thank you ❤️
happy to help