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?
Moaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.