0

When I'm trying to create dayEvent trpc is throwing this error:

TRPCClientError: 
Invalid `prisma.dayEvent.create()` invocation:


Null constraint violation on the fields: (`id`)

Here is trpc code that creates dayEvent:

create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({
        data: {
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),

Prisma schema:

model Calendar {
  id           String      @id @default(cuid())
  calendarName String
  dayEvents    dayEvent[]
  hostId       String

  host User @relation(fields: [hostId], references: [id])
}

model dayEvent {
  id         String   @id @default(cuid())
  name       String
  date       DateTime
  calendarId String

  calendar   Calendar @relation(fields: [calendarId], references: [id])
}

In Calendar @id @default(cuid()) is working, I can create calendars. But for some reason in dayEvent it wants id. When I give it id, like that:

create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({
        data: {
          id: '1',
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),

Everything is working as expected. Despite this, I don't think it will be right to generate ids like that with trpc.

Also here is client code that is triggering create.useMutation():

...
const createDayEvent = api.dayEvent.create.useMutation({
    onSuccess: () => {
      void refetchDayEvents()
    },
  })
...
return (
...
   <input
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              createDayEvent.mutate({
                date: currentDate,
                name:
                  e.currentTarget.value === ''
                    ? 'Event'
                    : e.currentTarget.value,
                calendarId: selectedCalendar?.id ?? '',
              })
              e.currentTarget.value = ''
              setIsCreatingDayEvent(false)
              setRenamingDayEventNow(false)
            }
          }}
        />

...
)

I expect @id @default(cuid()) to generate id as intended.

Grayza
  • 53
  • 10

0 Answers0