Data is not being successfully transmitted through the ORM (Prisma) to the database

After spending hours trying to solve this issue, I've hit a roadblock. My current project is using Next.js 13.

I managed to successfully connect my application to a Postgres Database, configure the Prisma schema, and test a migration with a seed.ts file.

The problem arises in my route.js file, which is causing various errors. When I submit the form, no data is being transmitted to the database, and I'm unable to identify why there's no error displaying in the console.

I've scoured through multiple Next.js 13 API forums, conducted Google searches, and watched YouTube tutorials. It seems like there might be an issue with the route.js file or possibly the API handler, but I'm stuck at this point without knowing what to debug.

Any assistance on this matter would be greatly appreciated.

route.js:

import { NextResponse } from 'next/server';
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function POST(req) {
    const { name, password, email } = req.body;
    try {

        const user = await prisma.user.create({
            data: {
                name,
                email,
                password
            },
        });
        return NextResponse.json({ message: 'method allow' })
    } catch (error) {
        return NextResponse.json({ message: 'error' })
        
    }
}

page.js (containing the form):


"use client";

import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function SignUp() {
    const { register, reset, formState: { errors }, handleSubmit } = useForm();
    const router = useRouter();
 
    const onSubmit = async data => {
        console.log(data);

        const user = await fetch("api/createuser", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(data),
        })

        /*if (Object.keys(errors).length === 0) {
            router.push("/login"); 
        }
        reset();

        */
    }
    return (
        <div>
            <h1 className="signUp">Sign up</h1>
            <form onSubmit={handleSubmit(onSubmit)} className="signUpForm">
                <input
                    {...register("name", { required: true })} id="first" placeholder="Name"
                    aria-invalid={errors.name ? "true" : "false"}
                />
                {errors.name?.type === 'required' && <p className="errorMessageOne" role="alert">First name is required</p>}

                <input {...register("mail", { required: true })} type="mail" id="email" placeholder="Email Address"
                    aria-invalid={errors.mail ? "true" : "false"} />
                {errors.mail && <p className="errorMessage" role="alert">Please enter a valid email address</p>}

                <input {...register("password", { required: true, minLength: 4 })} id="password" placeholder="Password must contain a minimum of 8 characters"
                    aria-invalid={errors.password ? "true" : "false"} />
                {errors.password && <p className="errorMessage" role="alert">Please enter a valid password</p>}

                <button type="submit" className="signSubmit">Submit</button>
                <p className="alreadyText"> Already have an account? <Link href="/login"><span>Login</span></Link></p>
            </form>
        </div>

    );
}

Answer №1

In your API route handler, the method you used to retrieve the JSON data from the form is specific to Next.js's pages router. However, since you are utilizing the app router, the approach differs as outlined in the documentation:

import { NextResponse } from 'next/server'
 
export async function POST(request) {
  const { name, password, email } = await request.json()
  // ...
}

Answer №2

If you encounter a similar issue, the following code snippet helped me successfully resolve it. This code now enables the submission of form data for storage in my local Postgres database through Prisma.

Route.js - Server component


import { NextResponse } from 'next/server';
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function POST(request) {

    const { name, password, email } = await request.json()

    const user = {
        name,
        email,
        password,
    }

    let createUser = await prisma.user.create({ data: user })

    return NextResponse.json(user)

}

page.js - Client Component

"use client"

import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation"; 
import Link from "next/link";

export default function SignUp() {
    const { register, reset, formState: { errors }, handleSubmit } = useForm();
    const router = useRouter();

    const onSubmit = async (data) => {
        try {
            const response = await fetch("/api/createuser", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(data),
            });

            if (response.ok) {
              
                router.push("/login");
                reset();
            } else {
              
                console.error("Registration failed");
            }
        } catch (error) {
            console.error("Error:", error);
        }
    };

    return (
        <div>
            <h1 className="signUp">Sign up</h1>
            <form onSubmit={handleSubmit(onSubmit)} className="signUpForm">
                <input
                    {...register("name", { required: true })}
                    id="first"
                    placeholder="Name"
                    aria-invalid={errors.name ? "true" : "false"}
                />
                {errors.name?.type === 'required' && <p className="errorMessageOne" role="alert">First name is required</p>}

                <input
                    {...register("email", { required: true })}
                    type="email" 
                    id="email"
                    placeholder="Email Address"
                    aria-invalid={errors.email ? "true" : "false"}
                />
                {errors.email && <p className="errorMessage" role="alert">Please enter a valid email address</p>}

                <input
                    {...register("password", { required: true, minLength: 4 })}
                    id="password"
                    placeholder="Password must contain a minimum of 8 characters"
                    aria-invalid={errors.password ? "true" : "false"}
                />
                {errors.password && <p className="errorMessage" role="alert">Please enter a valid password</p>}

                <button type="submit" className="signSubmit">Submit</button>
                <p className="alreadyText"> Already have an account? <Link href="/login"><span>Login</span></Link></p>
            </form>
        </div>
    );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Comparing the integration of apollo-client in next.js using `next-with-apollo` with the alternative method recommended in the next.js documentation FAQ (without relying on `getDataFromTree

Exploring the Contrasting Approaches of Implementing "apollo-client in next.js" in next-with-apollo npm library versus the method outlined in the next.js documentation. For the approach chosen by next.js for Apollo client integration, visit: https://githu ...

No information is currently present in the React Js Data Table

I am facing an issue with my React Js application. Even though my data table is getting populated successfully, it still displays "No data available in table" on the first row. You can view a screenshot of the displayed HTML by clicking on this link: https ...

Caution: A duplicate key was found in ReactJS when attempting to flatten children

Currently, I am utilizing Tabs from Material UI to showcase a List component that is filtered by the tab. Take a look at the code snippet below from my Container Component: <Tabs className="DrawerTabs" ...

react throws an error message stating "Invalid hook call" every time I attempt to utilize the material makestyles function

Just starting out with react and trying to implement makestyles, here's what I have: Inside Header.jsx : import React from "react"; import UseStyles from "./Header_style"; function Header() { const classes = UseStyles(); r ...

When utilizing an 'imported' asynchronous function, make sure to clean up the useEffect

Please do not mistake this for a duplicate. Despite my thorough search on various blogs and sources, I have yet to find a solution. My primary question is 'how can I address the error of react state change in unmounted component, and also cancel an a ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Verifying the accuracy of a React Component in interpreting and displaying a path parameter

I have the following React/Typescript component that is functioning correctly. However, I am struggling to write a test using testing-library. My goal is to verify that it properly receives the level parameter and displays it on the page: import React from ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...

Having trouble connecting to a recently installed PostgreSQL database through a php script

Having recently transitioned from MySQL to PostgreSQL, I installed PostgreSQL on my Fedora system and set up the postgres user following the instructions on the Fedora wiki. After creating the role using the psql shell while su-ing into the postgres user, ...

Attempting to optimize the onSubmit feature by utilizing Formik

Currently enhancing my development skills by working with React. I am looking to streamline the onSubmit property in my project. The application is a contact form built using the Formik component, which uploads data to Firebase Cloudstore and sends an emai ...

Navigate through a React interface with a Node.js backend routing system

As I embark on the journey of building a web application, I find myself facing some confusion. How can I effectively handle both React routing and Node routing? Is there a way to configure them to run on the same port? What is the best approach for imple ...

What could be causing Nextjs13 to fail in recognizing an authentication route, resulting in a 404 error?

I have been working on a project utilizing NextJs v13 with Strapi v4 as the backend. My project includes separate layouts for the site, login, and dashboard. While working on the login section, I implemented NextAuth for authentication. However, upon submi ...

What techniques can I use to customize React Bootstrap's css?

Struggling to find a way to override React Bootstrap css without resorting to inline styles. Currently working on rendering an Alert component. https://i.stack.imgur.com/KiATb.png Tried making some CSS modifications, but they're not taking effect du ...

Error in child component's class name with babel-plugin-react-css-modules

I'm currently implementing babel-plugin-react-css-modules in an existing React project. Most of the components are working as expected, but I've encountered an issue with passing styles to child components. My parent components look like this: ...

IE11 Error: Script1003 expected but not found

I'm in the process of adding IE11 support, but encountering the following errors: SCRIPT1003: Expected ':' File: vendor.bundle.js, Line: 8699, Column: 8 SCRIPT5009: 'webpackJsonp' is undefined File: app.bundle.js, Line: 1, Colum ...

Is there a way to manage or turn off the swipe snapshot feature utilized in IOS for navigating (using JS)?

I've been assigned the challenge of fixing a troublesome bug in my next.js application. The issue arises when navigating on IOS using touch gestures, causing the page content to flicker. It appears that the browser captures a snapshot of the heap and ...

Don't worry about Higher Order Components while conducting tests on React Components

Currently, I am attempting to test a straightforward Material UI select form that utilizes a FormControl and is exported with withStyles. In my testing scenario, the goal is quite simple: I wish to confirm that my component appropriately renders a child el ...

I am encountering an issue trying to create a Docker image featuring TypeScript

I am facing an issue while trying to build a docker image using the docker build . command in my next.js app An error is being encountered Error: buildx failed with: error: failed to solve: process "/bin/sh -c yarn run build" did not complete su ...

React beautiful dnd and Material UI list encountering compatibility problem

I recently encountered an issue while using react beautiful dnd to create a rearrangeable Material UI List. Everything was working correctly, except for the ListItemSecondaryAction within the list. When dragging a list item, the ListItemText and ListItemIc ...