I am creating a page to enter data into the database
This button saves or deletes data from the database. When the button is pressed, the API for the put operation works, but the API for the save and delete operation does not work.
How to solve the problem
ActionsButton Page
"use client"
import { ConfirmModal } from "@/components/modals/confirm-modal";
import { Button } from "@/components/ui/button";
import axios from "axios";
import { Trash } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";
interface ChapterActionsProps {
disabled: boolean;
courseId: string;
chapterId: string;
isPublished: boolean;
}
export const ChapterActions = ({
disabled,
courseId,
chapterId,
isPublished
}: ChapterActionsProps) => {
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const onClick = async () => {
try{
setIsLoading(true);
if(isPublished){
await axios.patch(`/api/courses/${courseId}/chapters/${chapterId}/Unpublish`);
toast.success("لم يتم الحفظ بعد");
}else{
await axios.patch(`/api/courses/${courseId}/chapters/${chapterId}/publish`);
toast.success("تم الحفظ");
}
}catch{
toast.error("حدث خطأ");
}finally{
setIsLoading(false);
}
}
const onDelete = async () => {
try {
await axios.delete(`api/courses/${courseId}/chapters/${chapterId}`);
toast.success("تم الحذف");
router.refresh();
router.push(`/teacher/courses/${courseId}`);
} catch {
toast.error("حدث خطأ");
} finally {
setIsLoading(false);
};
}
return (
<div className="flex items-center gap-x-2">
<Button
onClick={onClick}
disabled={disabled || isLoading}
variant="outline"
size="sm"
>
{isPublished ? "Unpublish" : "publish"}
</Button>
<ConfirmModal onConfirm={onDelete}>
<Button size="sm" disabled={isLoading}>
<Trash className="h-4 w-4" />
</Button>
</ConfirmModal>
</div>
)
}
api route
import Mux from "@mux/mux-node";
import { auth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server"
import { db } from "@/lib/db";
const Video = new Mux({
tokenId: process.env.MUX_TOKEN_ID,
tokenSecret: process.env.MUX_TOKEN_SECRET
});
export async function PATCH(
req: Request,
{ params }: { params: { courseId: string; chapterId: string } }
) {
try {
const { userId } = auth();
const { isPublished, ...values } = await req.json();
const mux = new Mux();
if (!userId) {
return new NextResponse("لايوجد تصريج", { status: 401 });
}
const ownCourse = await db.course.findUnique({
where: {
id: params.courseId,
userId
}
});
if (!ownCourse) {
return new NextResponse("لايوجد تصريج", { status: 401 });
}
const chapter = await db.chapter.update({
where: {
id: params.chapterId,
courseId: params.courseId,
},
data: {
...values,
}
});
if (values.videoUrl) {
const existngMuxData = await db.muxData.findFirst({
where: {
chapterId: params.chapterId,
}
});
if (existngMuxData) {
await Video.delete(existngMuxData.assetId);
await db.muxData.delete({
where: {
id: existngMuxData.id,
}
});
}
const asset = await mux.video.assets.create({
input: values.videoUrl,
playback_policy: ['public'],
encoding_tier: 'baseline',
test: false,
});
await db.muxData.create({
data: {
chapterId: params.chapterId,
assetId: asset.id,
playbackId: asset.playback_ids?.[0]?.id,
}
});
}
return NextResponse.json(chapter);
} catch (error) {
console.log("[COURSE_CHAPTER_ID]", error);
return new NextResponse("خطا في الأدخال", { status: 500 });
}
}
export async function DELETE(
req: Request,
{ params }: { params: { courseId: string; chapterId: string } }
) {
try {
const { userId } = auth();
const { isPublished, ...values } = await req.json();
if (!userId) {
return new NextResponse("لايوجد تصريج", { status: 401 });
}
const ownCourse = await db.course.findUnique({
where: {
id: params.courseId,
userId,
}
});
if (!ownCourse) {
return new NextResponse("لايوجد تصريج", { status: 401 });
}
const chapter = await db.chapter.findUnique({
where: {
id: params.chapterId,
courseId: params.courseId,
}
});
if (!chapter) {
return new NextResponse("لايوجد تصريج", { status: 404 });
}
if (chapter.videoUrl) {
const existingMuxData = await db.muxData.findFirst({
where: {
chapterId: params.chapterId,
}
});
if (existingMuxData) {
await Video.delete(existingMuxData.assetId);
await db.muxData.delete({
where: {
id: existingMuxData.id,
}
});
}
}
const deletedChapters = await db.chapter.delete({
where: {
id: params.chapterId,
}
});
const publishedChaptersInCourse = await db.chapter.findMany({
where: {
courseId: params.courseId,
isPublished: true,
}
});
if (!publishedChaptersInCourse.length) {
await db.chapter.update({
where: {
id: params.courseId,
},
data: {
isPublished: false,
}
});
}
return NextResponse.json(deletedChapters);
} catch (error) {
console.log("[COURSE_CHAPTER_ID_DELETE]", error);
return new NextResponse("خطا في الأدخال", { status: 500 });
}
}```
terminal error out
DELETE /teacher/courses/f884b08e-3dda-4942-b6cf-4180dd8a8024/chapters/api/courses/5efb9152-5e1f-4822-92e1-d2ec8f0f679f/chapters/5efb9152-5e1f-4822-92e1-d2ec8f0f679f 404 in 725ms
I tried to modify axios but it didn't work
New contributor
Othman Ai is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.