Next.js Discord

Discord Forum

DELETE Method using NextJs 15

Answered
Argente Brun posted this in #help-forum
Open in Discord
Argente BrunOP
Hey, how are you? I've got a problem I can't solve, I'm trying to dynamically delete data from my database, my route is working but I can't apply this in my component. Can you help me?```export async function DELETE(req: NextRequest) { try { const { id } = await req.json(); // Validation de l'ID if (!id || typeof id !== 'string') { return NextResponse.json({ message: 'ID is required and must be a string' }, { status: 400 }); } await prisma.service.delete({ where: { id, // Prisma attend une chaîne pour le champid`
},
});

return NextResponse.json({ message: 'Service deleted successfully' }, { status: 200 });
} catch (error) {
console.error(error);


return NextResponse.json(
{ message: 'Failed to delete service' },
{ status: 500 }
);
}
}```
Answered by joulev
DELETE requests do not have body, so await req.json() will return nothing
View full answer

6 Replies

Answer
Argente BrunOP
OK thank you 🙂
i would recommend moving the id to the URL instead, something like DELETE /api/products/:id
Argente BrunOP
OK nice
Argente BrunOP
const deleteService = async (id: string) => {
const previousServices = services;
setServices((values) => values.filter((item) => item.id !== id));

try {
const response = await fetch(
${process.env.NEXT_PUBLIC_URL}admin/services/service/${id},
{
method: "DELETE",
}
);

if (!response.ok) {
throw new Error("Failed to delete the service");
}
} catch (error) {
console.error("Error deleting service:", error);
setServices(previousServices);
}
};
good