i am working on a next.js web application. i am using vercel, postgreSQL and prisma. this is my prisma schema:
model entry {
no Int @id @default(autoincrement())
content String
cretedAt DateTime @default(now()) @db.Timestamp(0)
authorName String @db.VarChar(255)
baslikName String
baslik baslik @relation(fields: [baslikName], references: [title], onDelete: NoAction, onUpdate: NoAction)
}
model baslik {
id Int @id @default(autoincrement())
title String @unique @db.VarChar(255)
entries entry[]
}
there are topics called basliks and the users are supposed to submit entries to these baskliks.
baslik page has a submission form to submit entry to that baslik. this the code for baslik/page.js:
"use client"
import ClientComponent from "@/app/baslik/client-component";
import {useSearchParams} from "next/navigation";
export default function Page() {
const searchParams = useSearchParams()
const id = searchParams.get("id")// i use this searchParam to pick the spesific baslik
return (
<div>
<ClientComponent id={id} />
</div>
);
}
this is client component:
"use client";
import { useEffect, useState } from 'react';
import fetchBaslik from "@/app/baslik/server-component";
import Entry from "@/app/components/entry";
import styles from "./baslik.css";
import InputForm from "@/app/input/inputForm";
export default function ClientComponent({ id }) {
const [title, setTitle] = useState('');
const [entries, setEntries] = useState([]);
useEffect(() => {
async function getBaslik() {
const result = await fetchBaslik(id);
setTitle(result.title);
setEntries(result.entries);
}
if (id) {
getBaslik();
}
}, [id]);
return (
<div className={"baslik-main"}>
<h1>{title}</h1>
{entries.map(e => (
<Entry content={e.content} author={e.authorName} key={e.no}/>
))}
<InputForm baslikName={title}/>
</div>
);
}
server component:
"use server";
import { db } from "@/app/lib/prisdb";
export default async function fetchBaslik(id) {
const baslik = await db.baslik.findUnique({
where: {
id: Number(id)
},
include: {
entries: {
select: {
content: true,
authorName: true
}
}
}
});
// Ensure the result is a plain JSON object
return JSON.parse(JSON.stringify(baslik));
}
input form:
// InputForm.js
import React, { useState } from 'react';
import "./inputForm.css"
const InputForm = ({ baslikName }) => {
const [text, setText] = useState('');
const [nick, setNick] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('/api/addEntry', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ content: text, authorName: nick, baslikName: baslikName }),
});
if (!response.ok) {
throw new Error('Failed to add entry');
}
const result = await response.json();
setMessage('Entry added successfully');
setText('');
setNick('');
} catch (error) {
console.error('Error adding entry:', error);
setMessage('An error occurred');
}
};
return (
<div className="form-container">
<form className="entry-form" onSubmit={handleSubmit}>
<textarea
className="text-input"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Entry"
rows={4}
cols={15}
required
/>
<textarea
className="nick-input"
value={nick}
onChange={(e) => setNick(e.target.value)}
placeholder="Nick"
rows={2}
cols={15}
required
/>
<button type="submit" className="submit-button">Submit</button>
</form>
{message && <p>{message}</p>}
</div>
);
};
export default InputForm;
and addEntry file inside app/pages/api directory:
// pages/api/addEntry.js
import { db } from "@/app/lib/prisdb";
export default async function handler(req, res) {
if (req.method === 'POST') {
// Handle POST request
const { content, authorName, baslikName } = req.body;
// Validate required fields
if (!content || !authorName || !baslikName) {
return res.status(400).json({ error: 'Content, Author Name, and Baslik Name are required' });
}
try {
// Create new entry in the database
const newEntry = await db.entry.create({
data: {
content: content,
authorName: authorName,
baslikName: baslikName,
},
});
// Respond with the new entry
return res.status(200).json(newEntry);
} catch (error) {
// Handle database errors
console.error('Error adding entry:', error.message);
return res.status(500).json({ error: 'Failed to add entry' });
}
} else {
// Handle other HTTP methods
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
when you try to submit an entry to a baslik using input the input form, it doesn’t work. but i really can’t say which part of my code causes it. did i build the app wrong or i used wrong a file url? i’d really appreciate if you could help