Views count not updating in Next.js with Prisma #21307
-
QuestionI’m building a blog application using Next.js and Prisma. I have a page where I display a post based on its ID and I want to increment the views count each time this page is fetched. However, the views count doesn’t change at all. Here’s the relevant code: page.tsx: import BackButton from "@/components/BackButton";
import Badge from "@/components/Badge";
import DeleteButton from "@/components/DeleteButton";
import Like from "@/components/Like";
import Views from "@/components/Views";
import { Tag } from "@prisma/client";
import { Pencil } from "lucide-react";
import Link from "next/link";
interface Props {
params: {
id: string;
};
}
interface Post {
id: string;
title: string;
content: string;
tag: Tag;
views: number;
likes: number;
}
const getPost = async ({ params }: Props): Promise<Post> => {
const res = await fetch(`http://localhost:3000/api/posts/${params.id}`, {
cache: "no-store",
});
return res.json();
};
const DetailPage = async ({ params }: Props) => {
const post = await getPost({ params });
return (
<div className="flex flex-col gap-4 max-w-lg">
<BackButton href="/posts" />
<div className="flex justify-between gap-1 items-baseline max-w-sm">
<h1 className="text-3xl font-bold">{post.title}</h1>
{post.tag && <Badge tag={post.tag.name} />}
</div>
<div className="flex justify-start gap-4 items-baseline max-w-sm">
<div className="flex items-center gap-4">
<Link href={`/posts/edit/${post.id}`} className="btn btn-warning">
<Pencil /> Edit
</Link>
<DeleteButton params={params} />
</div>
<Views views={post.views} />
<Like likes={post.likes} />
</div>
<p className="max-w-md">{post.content}</p>
</div>
);
};
export default DetailPage; route.tsx: import prisma from "@/prisma/client";
import { NextRequest, NextResponse } from "next/server";
interface Props {
params: {
id: string;
};
}
export async function GET(req: NextRequest, { params }: Props) {
try {
const post = await prisma.post.update({
where: {
id: params.id,
},
data: {
views: {
increment: 1,
},
},
select: {
id: true,
title: true,
content: true,
tag: true,
views: true,
likes: true,
},
});
return NextResponse.json(post, { status: 200 });
} catch (error) {
return NextResponse.json(
{ message: "Could not fecth the post" },
{ status: 500 }
);
}
} views.tsx: import { Eye } from "lucide-react";
interface Props {
views: number;
}
const Views = ({ views }: Props) => {
console.log("****Views****: ", views);
return (
<div className="flex gap-1 items-center">
<Eye size={23} />
<span className="font-bold text-sm">{views}</span>
</div>
);
};
export default Views; prisma.schema.ts: generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model Tag {
id String @id @default(cuid()) @map("_id")
name String
post Post[]
}
model Post {
id String @id @default(cuid()) @map("_id")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String
views Int @default(0)
likes Int @default(0)
tag Tag? @relation(fields: [tagId], references: [id])
tagId String
}
Does anyone know why the views count might not be updating and how I can fix this? How to reproduce (optional)Expected behavior (optional)No response Information about Prisma Schema, Client Queries and Environment (optional)// Add your schema.prisma // Add any relevant Prisma Client queries here
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hello @MortezaIsvand 👋 What response do you get after invoking the Can you try enabling logging and check the underlying Mongo query that is generated? Is the View count value updated in the database? |
Beta Was this translation helpful? Give feedback.
-
I solved the problem with the views functionality. The problem occurred because I had created some posts before I defined the views field in the prisma.schema.ts file. As a result, these posts did not have the views field in the MongoDB Atlas database. To fix this, I used Prisma Studio to assign random views counts to each post manually. After that, all posts had the views count working properly. |
Beta Was this translation helpful? Give feedback.
I solved the problem with the views functionality. The problem occurred because I had created some posts before I defined the views field in the prisma.schema.ts file. As a result, these posts did not have the views field in the MongoDB Atlas database. To fix this, I used Prisma Studio to assign random views counts to each post manually. After that, all posts had the views count working properly.