Arghya Bag
Arghya Bag

Reputation: 1

tRPC Client Mutation Fails with "createUnhandledError" in Next.js

Problem Description I'm working on a Next.js project where I'm using tRPC to manage API requests. While implementing a mutation to create a project, I encountered the following error in the browser console:

Error Stack Tracetypescript[[ << mutation #1 ]project.createProject {}Call StackcreateUnhandledErrorfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_next_dist_client_9bb038..js (744:19)handleClientErrorfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_next_dist_client_9bb038..js (905:98)errorfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_next_dist_client_9bb038..js (1036:56)[project]/node_modules/@trpc/client/dist/links/loggerLink.mjs [app-client] (ecmascript)/defaultLogger/<file:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_2661d4..js (1250:15)logResultfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_2661d4..js (1286:31)errorfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_2661d4..js (1299:34)errorfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_@trpc_server_dist_072945..js (283:30)errorfile:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules@trpc_server_dist_072945..js (51:30)[project]/node_modules/@trpc/client/dist/links/httpBatchStreamLink.mjs [app-client] (ecmascript)/unstable_httpBatchStreamLink/</</</<file:/D:/PROJECTS/lunaris/.next/static/chunks/node_modules_2661d4..js (990:34)

**What I’m Trying to Achieve **I'm building a simple form to create a new project by sending data to the server using a tRPC mutation. Here's the client-side code for the form:

"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { api } from "@/trpc/react";
import React from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";

type FormInput = {
  repoUrl: string;
  projectName: string;
  githubToken?: string;
};

const CreatePage = () => {
  const { register, handleSubmit, reset } = useForm<FormInput>();
  const createProject = api.project.createProject.useMutation();

  function onSubmit(data: FormInput) {
    createProject.mutate(
      {
        githubUrl: data.repoUrl,
        name: data.projectName,
        githubToken: data.githubToken,
      },
      {
        onSuccess: () => {
          toast.success("Project Created Successfully");
          reset();
        },
        onError: (error) => {
          toast.error("Failed to create project");
          console.error("Mutation Error:", error);
        },
      }
    );
    return true;
  }

  return (
    <div className="flex h-full items-center justify-center gap-12">
      <img src="/undraw_github.svg" className="h-56 w-auto" />
      <div>
        <div>
          <h1 className="text-2xl font-semibold">Link your Github Repository</h1>
          <p className="text-sm text-muted-foreground">
            Enter the URL of your repository to link it to Lunaris!
          </p>
        </div>
        <div className="h-4"></div>
        <div>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Input
              {...register("projectName", { required: true })}
              placeholder="Project Name"
              required
            />
            <div className="h-2"></div>
            <Input
              {...register("repoUrl", { required: true })}
              placeholder="Github Url"
              type="url"
              required
            />
            <div className="h-2"></div>
            <Input {...register("githubToken")} placeholder="Github Token" />
            <div className="h-4"></div>
            <Button type="submit">Create Project</Button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default CreatePage;

Server-Side Setup On the server side, I have defined a Prisma model and a tRPC mutation.

Prisma Schema

generator client {
    provider = "prisma-client-js"
}

datasource db {
    provider = "postgresql"
    url      = env("DATABASE_URL")
}

model User {
    id        String   @id @default(cuid())

    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    imageURL  String?

    firstName      String?
    lastName       String?
    emailAddress     String   @unique

    credits    Int      @default(150)


    userToProjects UserToProject[]
}

model Project{
    id        String   @id @default(cuid())
    createdAt DateTime @default(now())      
    updatedAt DateTime @updatedAt

    name        String
    githubUrl   String

    deletedAt DateTime?

    userToProjects UserToProject[]
}

model UserToProject{
    id        String   @id @default(cuid())
    createdAt DateTime @default(now())      
    updatedAt DateTime @updatedAt

    userId    String
    projectId String

    user     User     @relation(fields: [userId], references: [id])
    project Project @relation(fields: [projectId], references: [id])

    @@unique([userId, projectId])
}

tRPC Router

import { z } from "zod";
import { createTRPCRouter, publicProcedure, protectedProcedure } from "../trpc";

export const projectRouter = createTRPCRouter({
    createProject: protectedProcedure.input(
        z.object({
            name: z.string(),
            githubUrl: z.string(),
            githubToken: z.string().optional()
        })
    ).mutation(async({ctx, input})=>{
        // const project =await ctx.db.project.create({
        //     data:{
        //         githubUrl: input.githubUrl,
        //         name: input.name,
        //         userToProjects:{
        //             create:{
        //                 userId: ctx.user.userId!,
        //             }
        //         }
        //     }
        // })
        console.log("input",input)
        return true
    })
})

Github repo for referance - link

Youtube video referance - link

Steps to Reproduce Clone the repository:

bash

git clone https://github.com/arghyabag/lunaris.git
cd lunaris

Install dependencies with Bun:

bash

bun install

Setup your environment variables:

Add a .env file in the root directory. Include the following variables: **env **

DATABASE_URL=your_postgres_connection_string
NEXTAUTH_SECRET=your_secret_key

Apply Prisma migrations:

bash

npx prisma migrate dev

Start the development server:

bash

bun dev

Access the application at http://localhost:3000.

Deployment with Bun Install Bun globally (if not already):

bash

curl -fsSL https://bun.sh/install | bash

Build the application for production:

bash

bun build

Run the production build:

bash

bun start

Ensure your environment variables are configured properly in your deployment setup.

I'm building a form to create a new project by sending data to the server via a tRPC mutation.

Upvotes: 0

Views: 90

Answers (1)

Yashasvi
Yashasvi

Reputation: 1

add &connect_timeout=10 at the end of your env variable. This error comes because your neon DB connection gets cut after 5 min of inactivity. Read about it in the following url: https://neon.tech/docs/guides/prisma#connection-timeouts

Upvotes: 0

Related Questions