t3-twitter-clone icon indicating copy to clipboard operation
t3-twitter-clone copied to clipboard

Unhandled Runtime Error TRPCClientError: Invalid `prisma.like.create()` invocation:

Open zmzlois opened this issue 2 years ago • 0 comments

Hey lads,

My model, tweet.ts and timeline did exactly the same as Tom until 1hr15mins in https://youtu.be/nzJsYJPCc80?t=4491 But when I clicked on the like it throw me an error

Unhandled Runtime Error
TRPCClientError: 
Invalid `prisma.like.create()` invocation:


Unique constraint failed on the fields: (`tweetId`,`userId`)

Call Stack
TRPCClientError.from
node_modules/@trpc/client/dist/transformResult-6fb67924.mjs (4:0)
eval
node_modules/@trpc/client/dist/links/httpBatchLink.mjs (190:39)

does anyone know why did this happen and how to fix it?

in case you need to see the code and my prisma model is

model Like {
  id            String    @id @default(cuid())
  tweet          Tweet      @relation(fields: [tweetId], references: [id])
  tweetId        String
  user          User      @relation(fields: [userId], references: [id])
  userId        String
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
  @@unique    ([tweetId, userId])
}

and my router code within server/router/tweets/ts looks like

import { z } from "zod";
import { protectedProcedure, publicProcedure, router } from "../trpc";
import { tweetSchema } from "../../../components/CreateTweet";

export const tweetRouter = router({
...
like: protectedProcedure
    .input(
      z.object({
        tweetId: z.string(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const { prisma } = ctx;

      const userId = ctx.session.user.id;

      return prisma.like.create({
        data: {
          tweet: {
            connect: {
              id: input.tweetId,
            },
          },
          user: {
            connect: {
              id: userId,
            },
          },
        },
      });
    }),

while on the front end it looks like

function Tweet({
  tweet,
}: {
  tweet: RouterOutputs["tweet"]["timeline"]["tweets"][number];
}) {
  const likeMutation = trpc.tweet.like.useMutation().mutateAsync;
....
return(
 <div className="flex-grid ml-2 flex  gap-3">
        <AiFillHeart
          color="grey"
          size="1rem"
          className="mt-0.5"
          onClick={() => {
            likeMutation({ tweetId: tweet.id });
          }}
        />
</div>
)

not sure what went wrong

zmzlois avatar Dec 30 '22 07:12 zmzlois