skip to Main Content

I’m working on a Next.js project where I fetch grades from a database using Prisma in the app directory. The fetched data is displayed using a GradesComponent. However, when I run npm run build, the page generates static files with the data that was in the database at the time of the build. Any subsequent changes to the database are not reflected on the page.

Here is the relevant code:

app/page.tsx

import { getGrades } from "@/actions/getGrades";
import { GradesComponent } from "./Grades";

export default async function Home() {
  const grades = await getGrades();
  return (
    <div>
      <h1>Grades</h1>
      <p>Grades will be displayed</p>
      <GradesComponent grades={grades} />
    </div>
  );
}

app/Grades.tsx

import { Grades } from "@prisma/client";

export const GradesComponent = ({ grades }: { grades: Grades[] | null }) => {
  return (
    <div>
      <h1>Grades</h1>
      {grades?.map((grade) => (
        <div key={grade.id}>
          <h2>{grade.title}</h2>
          <p>{grade.grade}</p>
        </div>
      ))}
    </div>
  );
};

actions/getGrades.ts

import { db } from "@/lib/db";

export const getGrades = async () => {
  try {
    const grades = await db.grades.findMany();
    console.log(grades);
    return grades;
  } catch (e) {
    console.error(e);
    return null;
  }
};

I want the page to fetch the latest data from the database on each request, not just during the build process. How can I achieve this with Next.js, Prisma, and the App Router?

Note

When I run npm run dev, everything works perfectly. The data updates after a refresh, reflecting the latest changes from the database.

2

Answers


  1. Have you tried revalidation?
    export const revalidate = 60;
    Add this in ur layout or template.js

    Login or Signup to reply.
  2. If you want to fetch the latest data from the database on each request then it’s better to use React.useEffect().
    NextJS will cache the data.

    More about Data Fetching, Caching, and Revalidating

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search