KDT-IaaS-Class-One-Group / KDT-IaaS-1team-ERP

0 stars 2 forks source link

user 고객센터 - 페이지 네이션 버튼 위치 footer밑으로 갔음 #93

Closed csm009177 closed 7 months ago

csm009177 commented 7 months ago

"use client"; // 필요한 의존성을 가져옵니다. import React, { useState, useEffect, useCallback, ChangeEvent } from "react";

// BoardInfo 인터페이스를 정의합니다. interface BoardInfo { titleKey: string; adddate: string; username: string; password: string; title: string; content: string; reply: string; }

// Page 컴포넌트를 생성합니다. export default function Board() { // 데이터 및 UI 상태를 관리하는 상태 변수들입니다. const [boards, setBoards] = useState<BoardInfo[]>([]); const [pageInfo, setPageInfo] = useState({ currentPage: 1, pageSize: 10, totalPages: 1, });

const pageSize = 10; const [showForm, setShowForm] = useState(false); const [boardInfo, setBoardInfo] = useState({ titleKey: "", adddate: "", username: "", password: "", title: "", content: "", reply: "", }); const [selectedBoard, setSelectedBoard] = useState<BoardInfo | null>(null);

// 서버에서 게시판 데이터를 가져오는 함수입니다. const fetchData = useCallback(async (page: number) => { try { let apiUrl = /api/qna?page=${page}&pageSize=${pageSize};

  const response = await fetch(apiUrl);
  const data = await response.json();

  setBoards(data.boards); // null 또는 undefined가 아닐 경우에만 설정
  setPageInfo({
    currentPage: data.pageInfo.currentPage,
    pageSize: data.pageInfo.pageSize,
    totalPages: data.pageInfo.totalPages,
  });
} catch (error) {
  console.error("데이터를 불러오는 중 오류 발생:", error);
}

}, []);

const [inputPassword, setInputPassword] = useState(""); const handleInputChange = ( e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement> ) => { const { name, value } = e.target; setBoardInfo((prevBoardInfo) => ({ ...prevBoardInfo,

}));

};

const handleModalClose = () => { setShowForm(false); setSelectedBoard(null); setInputPassword(""); // 모달 닫을 때 비밀번호 초기화 };

const handlePasswordCheck = () => { // 입력한 비밀번호와 글의 비밀번호 비교 if (inputPassword === selectedBoard?.password) { alert("비밀번호 일치! 글을 표시합니다."); } else { alert("비밀번호가 일치하지 않습니다."); } };

// 현재 시간 const formatDateTime = (date: string) => { const dateObject = new Date(date); const options: Intl.DateTimeFormatOptions = { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", timeZone: "Asia/Seoul", }; const dateTimeString = dateObject.toLocaleString("ko-KR", options); return dateTimeString; };

const handleWriteButtonClick = () => { if (!showForm) { setShowForm(true); setBoardInfo({ titleKey: "", adddate: "", username: "", password: "", title: "", content: "", reply: "", }); setSelectedBoard(null); // 글쓰기 모달이 열릴 때 선택된 게시글 초기화 setInputPassword(""); } };

const handleSubmit = async () => { // content(내용) 필드가 비어 있는지 확인 if (!boardInfo.content.trim()) { alert("내용을 입력하세요."); // 원하는 방식으로 알림을 표시하거나 검증 오류를 처리하세요 return; }

try {
  const response = await fetch("/api/qnawrite", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(boardInfo),
  });

  if (response.ok) {
    fetchData(pageInfo.currentPage);
    alert("등록 완료");
  } else {
    console.error(`게시글 추가 중 오류 발생: ${response.status}`);
    alert("등록 실패");
  }

  // 모달 닫기
  setShowForm(false);
} catch (error) {
  console.error("게시글 추가 중 오류 발생:", error);
}

};

// 컴포넌트 마운트 또는 페이지 변경 시 데이터를 가져오는 효과입니다. useEffect(() => { fetchData(pageInfo.currentPage); }, [fetchData, pageInfo.currentPage]);

// 페이징 변경을 처리하는 이벤트 핸들러입니다. const handlePageChange = async (newPage: number) => { // 페이지 이동 중 로딩 상태를 보여줄 수 있는 UI 추가 setBoards([]); setPageInfo({ ...pageInfo, currentPage: newPage, });

try {
  let apiUrl = `/api/qna?page=${newPage}&pageSize=${pageSize}`;
  const response = await fetch(apiUrl);
  const data = await response.json();

  console.log("Fetched data:", data);

  setBoards(data.boards || []);
  setPageInfo({
    currentPage: data.pageInfo.currentPage,
    pageSize: data.pageInfo.pageSize,
    totalPages: data.pageInfo.totalPages,
  });
} catch (error) {
  console.error("데이터를 불러오는 중 오류 발생:", error);
}

};

const handleRowClick = async (board: BoardInfo) => { const enteredPassword = prompt("비밀번호를 입력하세요:");

if (enteredPassword === board.password) {
  setShowForm(false);
  setSelectedBoard(board);
} else {
  alert("비밀번호가 일치하지 않습니다.");
}

};

return (

Q&A 게시판

{showForm && (

글쓰기


×
)}
{boards.map((board) => ( ))}
Title Key Add Date Username Title Reply Actions
{board.titleKey} {formatDateTime(board.adddate)} {board.username} {board.title} {board.reply}
{selectedBoard && (
×

titleKey : {selectedBoard.titleKey}

adddate : {formatDateTime(selectedBoard.adddate)}
username : {selectedBoard.username}
title : {selectedBoard.title}
content : {selectedBoard.content}
reply : {selectedBoard.reply}
)}
{Array.from( { length: pageInfo.totalPages }, (_, index) => index + 1 ).map((pageNumber) => ( ))}

); }