
체크박스는 headlessui 라이브러리를 사용하여 구현하였고 아래 사진이 기본적인 예시이다.

전체를 선택할 때도 있을 것이고 n개를 선택할 때도 있을 것임.
그러므로 이를 삭제할 때를 대비하여 체크한 값들의 id값을 배열 형식으로 저장하고자 하였음.
const { remove } = useBucket();
const [ids, setIds] = useState<string[]>([]);
위의 코드를 통해 ids를 배열로 관리하여 remove 메서드에 ids를 전달해주는 방식이다.
이를 잘 구현하기 위해선 서버단의 코드가 중요했는데 아래와 같이 작성하였음.
export async function DELETE(req: NextRequest) {
try {
const { ids } = await req.json();
if (!Array.isArray(ids) || ids.length === 0) {
return NextResponse.json(
{ error: MESSAGE.ERROR_MESSAGE.noData },
{ status: 400 }
);
}
for (const id of ids) {
const getResponse = await fetch(`http://localhost:5000/bucket?id=${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await getResponse.json();
if (data.length === 0) {
return NextResponse.json(
{ message: `${MESSAGE.ERROR_MESSAGE.noData}` },
{ status: 404 }
);
}
for (const item of data) {
await fetch(`http://localhost:5000/bucket/${item.id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
}
}
return NextResponse.json({
message: "선택한 모든 데이터를 성공적으로 삭제했습니다.",
});
} catch (e) {
console.error(`${MESSAGE.ERROR_MESSAGE.delete}`, e);
return NextResponse.json({ error: "장바구니 삭제 실패" }, { status: 500 });
}
}
기존의 데이터를 알아보기 위해선는 한번 호출을 해야 했고, 전달받은 id의 값에 맞는 데이터들을 얻어왔고 해당 값이 존재한다면 그 데이터들에 대한 delete 명령을 보내주었다.
그렇다면 해당 데이터의 order값만 +1해주어야 했음.
그래서 미리 작성해놨던 POST http method의 로직을 아래와같이 수정함
export async function POST(req: NextRequest, res: NextResponse) {
try {
const { data } = await req.json();
const existingItemResponse = await fetch(
`http://localhost:5000/bucket?id=${data.id}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
);
const existingItems = await existingItemResponse.json();
let response;
if (existingItems.length > 0) {
const updatedItem = {
...existingItems[0],
order: existingItems[0].order + 1,
};
response = await fetch(
`http://localhost:5000/bucket/${existingItems[0].id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedItem),
}
).then((res) => res.json());
} else {
const newItem = { ...data, order: 1 };
response = await fetch("http://localhost:5000/bucket", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newItem),
}).then((res) => res.json());
}
return NextResponse.json(response);
} catch (e) {
throw new Error("장바구니 추가 실패");
}
}
해당 아이디의 데이터가 존재한다면? order만 +1 아니라면 order가 1인채로 생성해달라고 로직을 작성하게 되었음.
이제 결제 기능 하러 가볼까..