Next.js Discord

Discord Forum

trayng to create data using nextjs and prisma sqlite

Unanswered
DeFc0n posted this in #help-forum
Open in Discord
a

111 Replies

here is my handler
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../prisma/client";

export default async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method !== "POST") {
    return res.status(405).json({ message: "method not allowed" });
  }
  const transData = JSON.parse(req.body);

  const saveData = await prisma.transaction.create({
    data: transData,
  });
  res.json(saveData);
};
Plott Hound
what version of next are you using?
latest
Plott Hound
app router?
yes
Plott Hound
this is wrong:
export default async (req: NextApiRequest, res: NextApiResponse) => {
read the docs for proper syntax: https://nextjs.org/docs/app/building-your-application/routing/route-handlers

eg export async function POST() {
Plott Hound
your code is from older version of next
if you still have problems share your error logs
there are no error logs the data in trayng to create dosnt create
Plott Hound
yeah you need to add console logs to your route handler to actually see what errors are happening.
i just added some to your non working code as an example:
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../prisma/client";

export default async (req: NextApiRequest, res: NextApiResponse) => {
  console.log("Request received", req.method);

  if (req.method !== "POST") {
    console.log("Non-POST method received");
    return res.status(405).json({ message: "method not allowed" });
  }
  
  console.log("Request body:", req.body);
  const transData = JSON.parse(req.body);
  console.log("Parsed transaction data:", transData);

  try {
    const saveData = await prisma.transaction.create({
      data: transData,
    });
    console.log("Data saved successfully:", saveData);
    res.json(saveData);
  } catch (error) {
    console.error("Error saving data:", error);
    res.status(500).json({ message: "Internal server error" });
  }
};
your code should look something like this in next14:
// app/api/your-route-name/route.ts
import prisma from "../../prisma/client";

export async function POST(req: Request) {
  const transData = await req.json();

  const saveData = await prisma.transaction.create({
    data: transData,
  });

  return new Response(JSON.stringify(saveData), {
    headers: {
      'Content-Type': 'application/json',
    },
  });
}
OHHHH
thank you
and make sure to protect that route to minimise access for other users 🙂
im using clerk the entire project is locked with login,
Plott Hound
yeah exactly what Risky said. Also while its fine to use api routes/ route handlers, in Next14 we are encouranged to use Server Actions. so check the docs for those. it would be more applicable to your code
remember console logs are your friend. its the fastest way to figure out why something isnt working
@Plott Hound remember console logs are your friend. its the fastest way to figure out why something isnt working
i added a bunch none of them send anythink, i think i have coded the table wrong
Plott Hound
share the front end code that is trying to access this api route pls
@DeFc0n Click to see attachment
its this one, without console logs though
Plott Hound
remember in the route handler the logs will show up in the server console (vscode) not in the browser since its happening on the server
yes i know, nothing shows up
@DeFc0n yes i know, nothing shows up
Plott Hound
going back to work now, but i'd add a bunch of logging to your front end and see why its failing. you could even just paste it in chatGPT and say add a bunch of console logs to this
@DeFc0n alright thank you
how are you accesing the routes?
const handleSubmit = async (e) => {
    console.log("handleSubmit");
    e.preventDefault();

    console.log("Submitting formData:", formData);
    try {
      const response = await fetch("/api/transactions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error(response.statusText);
      }

      const result = await response.json();
      console.log("Transaction created:", result);

      // Clear the form
      setFormData({
        type: "",
        amount: "",
        description: "",
      });
      console.log("Cleared formData:", formData);
    } catch (error) {
      console.error("Error saving transaction:", error);
    }
  };
have you tried accesing your route via postman/curl/rest
i have not, let install postman,
just do this
hmm that might be hard to insert JSON object
not sure but i think its not reaching the api
yes
so i think its the problem with handleSubmit
the logs agree
when i click the button no logs show
then how you did you set up handleSubmit on the buttons :v
<form onSubmit={handleSubmit}>
<button
onSubmit={handleSubmit}
type="submit"
className="text-blue-500"
>
Submit
</button>
none of them work,
does the console.log("handleSubmit"); work
postman returns error 404 not found
send client side code
of how you setup the <form>
weird af
any console messages on the browser?
nope
should i re install node modules
hmmm
try making a new form
a simple form on your project
and focus on handleSubmit, <form> and <button>
ok
@aardani and focus on handleSubmit, <form> and <button>
i comented out everythink apart these, still nothing
this is very odd
very odd indeed
are you running on npm run dev and not npm run start?
yes npm run dev
try using onClick instead of onSubmit for buttons
and try using action instead of onSubmit for form
i mean, vercel dev takes things from your actual vercel thing (ie env vars) and does some things with it... idk if it can change that much wait wrong thread 😭
(try one at a time)
yeah do what alfon said 🙂
@aardani and try using action instead of onSubmit for form
this though, nothing happens, even the form does not clear
@DeFc0n haha, no problem
yeah i saw npm run dev and one just before was doing vercel dev vs npm dev, sorry again
ok
try creating a new project 😭 and create form in there
very odd indeed
i dont even know how you got it this far ngl 🫠
yeahh
first time doing a project in windows
not suprising if windows messed up lol
shouldnt be that hard
just npm run dev and open in browser :/
easier in linux
lazy to do a whole new rice with arch
reinstalled node modules
nothing lol,
ima re do table.jsx\
@aardani i found out what i did wrong
what did you do wrong
in api i had api/transactions.js not /api/transactions/route.js
i hope this is the biggest facepalm ive ever seen
but did it fix the issue?
nah,
that thing still nothing LOL
re doing it hopefully it will work now
.......................
i know im stupid
no
stop saying you are stupid people, ive seen that twice
LETSSSSSSSSSS GOOOOOOOOOOOOOOOOOOOO
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
i can now create data,
using postman
Plott Hound
haha had to come back and see how you got on. glad you figured it out XD
@Plott Hound haha had to come back and see how you got on. glad you figured it out XD
ha ye, thanks now i just need to add the UI
Plott Hound
whenever i make a route handler i visit the physical url of it to make sure it responds, good practice
im getting more odd bugs and stuff aparatly my code is good but it dosnt work