[TypeScript]_페이지네이션

hanseungjune·2023년 3월 27일
0

비전공자의 IT준비

목록 보기
59/68
post-thumbnail

📌 현재 작성중인 코드 일부분

이거 JS로 사실 올린거니까. 나중에 타입이랑 CSS 변경해야함.

//MUI 컴포넌트
import * as React from 'react';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

import axios from "axios";
import { API_URL, CARBORN_SITE } from "./../../../lib/api";
import { useEffect, useState } from "react";
import styled from "@emotion/styled";
import { useNavigate } from "react-router-dom";

const InspectorContentPagination = ({
  itemsPerPage,
}) => {
  const navigate = useNavigate();
  const [currentPage, setCurrentPage] = useState(1);
  const [inspectorData, setInspectorData] = useState([]);
  const [totalPageCnt, setTotalPageCnt] = useState(0);

  const handleRequestInspectorData = async (page, count) => {
    try {
      const response = await axios.get(`${CARBORN_SITE}/api/user/inspect/book/list/${page}/${count}`);
      console.log(response.data.message)
      
      setTotalPageCnt(response.data.message.totalPages);
      
      const modifiedContent = response.data.message.content.map((content: any) => {
        let modifiedBookStatus = '';
        let modifiedBookStatusNum = 0;
        switch (content.bookStatus) {
          case 0:
            modifiedBookStatus = '예약 중';
            modifiedBookStatusNum = 0;
            break;
          case 1:
            modifiedBookStatus = '검수 완료';
            modifiedBookStatusNum = 1;
            break;
          case 2:
            modifiedBookStatus = '예약 취소';
            modifiedBookStatusNum = 2;
            break;
          default:
            modifiedBookStatus = content.bookStatus;
            modifiedBookStatusNum = 0;
            break
        }
  
        return {
          ...content,
          bookStatus: modifiedBookStatus,
          modifiedBookStatusNum,
        };
      });
  
      setInspectorData(modifiedContent);
      setCurrentPage(page);
    } catch (error) {
      console.error(error);
    }
  };
  
  const ObjString: string | null = localStorage.getItem("login-token");
  const Obj = ObjString ? JSON.parse(ObjString) : null;
  
  const totalPages = totalPageCnt;

  useEffect(() => {
    handleRequestInspectorData(currentPage, itemsPerPage);
  }, [currentPage, itemsPerPage]);

  if (inspectorData.length === 0) {
    return <div>No data Found!</div>;
  }

  const getInspectorBookDetail = (carId: number) => {
    if (Obj.userId) {
      navigate(`/${Obj.userId}/mypage/inspector/${carId}/bookdetail`);
    }
  };
  
  const getInspectorDetail = (resultId: number) => {
    if (Obj.userId) {
      navigate(`/${Obj.userId}/mypage/inspector/${resultId}/completedetail`, {
        state: inspectorData[resultId % 5],
      });
    }
  };
  

  return (
    <StyleInspectorPaginationDiv>
      <table>
        <thead>
          <tr>
            <th>차량모델</th>
            {/* <th>제조사</th> */}
            <th>{`주행거리(km)`}</th>
            <th>차량번호</th>
            <th>{`연식(년)`}</th>
            <th>검수예약신청일</th>
            {/* <th>검수완료일</th> */}
            <th>검수상태</th>
            <th>검수업체</th>
            <th>예약상세조회</th>
            <th>완료상세조회</th>
          </tr>
        </thead>
        <tbody>
          {inspectorData.map((car, index) => (
            <tr key={index}>
              <td>{car.carModelNm}</td>
              {/* <td>{car.manufacturer}</td> */}
              <td>{car.carMileage}</td>
              <td>{car.carRegNm}</td>
              <td>{car.carModelYear}</td>
              <td>
                {car.bookDt === null ? "-" : car.bookDt}
              </td>
              {/* <td>
                {car.lastMaintenanceDate === null
                  ? "-"
                  : car.lastMaintenanceDate}
              </td> */}
              <td>{car.bookStatus}</td>
              <td>{car.inspectorAccountName}</td>
              {/* <td>
                {car.maintenanceCompany === null ? "-" : car.maintenanceCompany}
              </td> */}
              <td>
                <button onClick={() => getInspectorBookDetail(car.id)}>
                  조회
                </button>
              </td>
              <td>
                <button onClick={() => getInspectorDetail(car.id)}>
                  조회
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <div>
        <button
          disabled={currentPage === 1}
          onClick={() => handleRequestInspectorData(currentPage - 1, itemsPerPage)}
        >
          Previous
        </button>
        {Array.from({ length: totalPages }, (_, i) => {
          if (i >= currentPage + 2 || i <= currentPage - 2) return null;
          return (
            <button
              key={i}
              disabled={currentPage === i + 1}
              onClick={() => handleRequestInspectorData(i + 1, itemsPerPage)}
            >
              {i + 1}
            </button>
          );
        })}
        <button
          disabled={currentPage === totalPages}
          onClick={() => handleRequestInspectorData(currentPage + 1, itemsPerPage)}
        >
          Next
        </button>
      </div>
      <div>
        <Stack direction="row" spacing={2}>
          <Pagination
            count={totalPages}
            page={currentPage}
            color="primary"
            onChange={(event, page) =>
              handleRequestInspectorData(page, itemsPerPage)
            }
          />
        </Stack>
      </div>
    </StyleInspectorPaginationDiv>
  );
};

export default InspectorContentPagination;

// 페이지네이션 컴포넌트 (MUI)
export const BasicPagination = () => {
  return (
    <Stack spacing={2}>
      <Pagination count={10} color="primary" />
    </Stack>
  );
}
profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글