Check out the code in createComment.ts file, which serves as a Next.js api route:
import type { NextApiRequest, NextApiResponse } from 'next'
import sanityClient from "@sanity/client"
const config = {
dataset: process.env.NEXT_PUBLIC_SANITY_DATSET,
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
useCdn: process.env.NODE_ENV === "production",
token: process.env.SANITY_API_TOKEN
}
const client = sanityClient(config);
export default async function createComment(
req: NextApiRequest,
res: NextApiResponse
) {
const {_id, name, email, comment} = req.body
try {
await client.create({
_type: 'comment',
post: {
_type: "reference",
_ref: _id
},
name,
email,
comment
})
} catch (error) {
return res.status(500).json({message: "Couldn't submit comment", error})
}
console.log("Comment submitted")
res.status(200).json({ message: 'Comment Submitted Successfully' })
}
Additionally, here is the frontend code that utilizes Fetch API to send a POST request to the above-mentioned api route:
const onSubmit: SubmitHandler<IFormInput> = (data) => {
fetch("/api/createComment", {
method: "POST",
body: JSON.stringify(data),
})
.then(() => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
};
Despite repeated attempts such as clearing cache and restarting the server, an error persists.