[SI]공공데이터 포털 오픈 api 사용하여 음식점정보 불러오기

src - pages - thema-load - ThemaLoadList.tsx 생성

ThemaLoadList.tsx

// ThemaLoadList.tsx : rfce
// 공공 데이터 포털 : 부산 테마거리 전체 조회
import { Pagination } from "@mui/material";
import React, { useEffect, useState } from "react";
import TitleCom from "../../../components/common/TitleCom";
import IThemaLoad from './../../../types/shop/IThemaLoad';
import ThemaLoadService from "../../../services/shop/ThemaLoadService";

function ThemaLoadList() {
  // todo: 변수 정의
  // themaLoad 배열 변수
  const [themaLoad, setThemaLoad] = useState<Array<IThemaLoad>>([]);

  // todo: 공통 변수 : page(현재페이지번호), count(총페이지건수), pageSize(3,6,9 배열)
  const [page, setPage] = useState<number>(1);
  const [count, setCount] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(3); // 1페이지당개수
  // todo: 공통 pageSizes : 배열 (셀렉트 박스 사용)
  const pageSizes = [3, 6, 9];

  // todo: 함수 정의
  useEffect(() => {
    retrieveThemaLoad(); // 전체 조회
  }, [page, pageSize]);

  //   전체조회 함수
  const retrieveThemaLoad = () => {
    ThemaLoadService.getAll(page -1, pageSize) // 벡엔드 전체조회요청
    .then((response: any)=>{
      // todo : 공공 API 결과 값 저장
      // todo : totalCount(총건수), data(결과값배열)
      // todo :  perPage(1페이지당개수)
      // todo : 총페이지수 = Math.ceil(totalCount / perPage)
      const { data, perPage, totalCount } = response.data;
      // 총페이지 수
      const totalPages = Math.ceil(totalCount / perPage);
      setThemaLoad(data);
      setCount(totalPages);
      console.log("response", response.data);

    })
    .catch((e: Error)=>{
      // 벡엔드 실패시 실행됨
      console.log(e);
    })
  };

  // todo: handlePageSizeChange(공통) : pageSize 값 변경시 실행되는 함수
  //  select 태그 수동 바인딩 : 화면값 -> 변수에 저장
  const handlePageSizeChange = (event: any) => {
      setPageSize(event.target.value); // 1페이지당 개수저장(3,6,9)
      setPage(1); // 현재페이지번호 : 1로 강제설정
   }

  //  todo: Pagination 수동 바인딩(공통)
  //  페이지 번호를 누르면 => page 변수에 값 저장
  const handlePageChange = (event:any, value:number) => {
      // value == 화면의 페이지번호
      setPage(value);
   }  

  return (
    // 여기
    <>
      {/* 제목 start */}
      <TitleCom title="ThemaLoad List" />
      {/* 제목 end */}

      {/* paging 시작 */}
      <div className="mt-3">
        {"Items per Page: "}
        <select onChange={handlePageSizeChange} value={pageSize}>
          {pageSizes.map((size) => (
            <option key={size} value={size}>
              {size}
            </option>
          ))}
        </select>

        <Pagination
          className="my-3"
          count={count}
          page={page}
          siblingCount={1}
          boundaryCount={1}
          variant="outlined"
          shape="rounded"
          onChange={handlePageChange}
        />
      </div>
      {/* paging 끝 */}

      {/* table start */}
      <div className="col-md-12">
        {/* table start */}
        <table className="table">
          <thead className="table-light">
            <tr className="text-center">
              <th scope="col">식당(ID)</th>
              <th scope="col">식당명</th>
              <th scope="col">지역명</th>
              <th scope="col">식당이미지(ID)</th>
              <th scope="col">식당이미지(URL)</th>
              <th scope="col">Actions</th>
            </tr>
          </thead>
          <tbody>
            {themaLoad &&
              themaLoad.map((data, index) => (
                <tr key={index} className="text-center">
                  <td>{data["식당(ID)"]}</td>
                  <td>{data["식당명"]}</td>
                  <td>{data["지역명"]}</td>
                  <td>{data["식당이미지(ID)"]}</td>
                  <td>
                    <img
                      src={data["식당이미지(URL)"]}
                      width="50vw"
                      height="30vh"
                    />{" "}
                  </td>
                </tr>
              ))}
          </tbody>
        </table>
        {/* table end */}
      </div>
      {/* table end */}
    </>
  );
}

export default ThemaLoadList;

 


app.tsx

import React from "react";
// app css import
import "./assets/css/app.css";

import HeaderCom from "./components/common/HeaderCom";
import { Route, Routes } from "react-router-dom";
import Home from "./pages/Home";
import Login from "./pages/auth/Login";
import Register from "./pages/auth/Register";
import ForgotPassword from "./pages/auth/ForgotPassword";
import NotFound from "./pages/common/NotFound";
import DeptList from "./pages/basic/dept/DeptList";
import EmpList from "./pages/basic/emp/EmpList";
import AddDept from "./pages/basic/dept/AddDept";
import AddEmp from "./pages/basic/emp/AddEmp";
import Dept from "./pages/basic/dept/Dept";
import Emp from "./pages/basic/emp/Emp";
import QnaList from "./pages/basic/qna/QnaList";
import CustomerList from "./pages/basic/customer/CustomerList";
import AddQna from "./pages/basic/qna/AddQna";
import AddCustomer from "./pages/basic/customer/AddCustomer";
import Qna from "./pages/basic/qna/Qna";
import Customer from "./pages/basic/customer/Customer";
import FaqList from "./pages/normal/faq/FaqList";
import CinemaFaqList from "./pages/normal/cinema/CinemaFaqList";
import AddFaq from "./pages/normal/faq/AddFaq";
import AddCinemaFaq from "./pages/normal/cinema/AddCinemaFaq";
import Faq from "./pages/normal/faq/Faq";
import CinemaFaq from "./pages/normal/cinema/CinemaFaq";
import ReplyBoardList from "./pages/normal/reply-board/ReplyBoardList";
import ThreadBoardList from "./pages/normal/thread-board/ThreadBoardList";
import AddReplyBoard from "./pages/normal/reply-board/AddReplyBoard";
import AddThreadBoard from "./pages/normal/thread-board/AddThreadBoard";
import ReplyBoard from "./pages/normal/reply-board/ReplyBoard";
import ThreadBoard from "./pages/normal/thread-board/ThreadBoard";
import CodeCategoryList from "./pages/admin/CodeCategoryList";
import AddCodeCategory from "./pages/admin/AddCodeCategory";
import CodeList from "./pages/admin/CodeList";
import AddCode from "./pages/admin/AddCode";
import Code from "./pages/admin/Code";
import SimpleProductList from "./pages/shop/simple-product/SimpleProductList";
import ProductList from "./pages/shop/product/ProductList";
import AddSimpleProduct from "./pages/shop/simple-product/AddSimpleProduct";
import SimpleProduct from "./pages/shop/simple-product/SimpleProduct";
import SimpleCart from "./pages/shop/simple-product/SimpleCart";
import AddProduct from "./pages/shop/product/AddProduct";
import Product from "./pages/shop/product/Product";
import SimpleCartList from "./pages/shop/simple-product/SimpleCartList";
import CinemaList from "./pages/shop/cinema/CinemaList";
import Cinema from "./pages/shop/cinema/Cinema";
import ThemaLoadList from "./pages/shop/thema-load/ThemaLoadList";
import FileDbList from "./pages/advanced/FileDbList";

function App() {
  return (
    <div className="App">
      <HeaderCom />

      {/* <!-- 구분 막대 시작 --> */}
      <div className="gutter text-center text-muted fade-in-box">
        <div>클론 코딩 예제 사이트에 오신 것을 환영합니다.</div>
      </div>
      {/* <!-- 구분 막대 끝 --> */}

      <div id="content-wrapper">
        {/* 라우터 정의 시작 */}
        <Routes>
          {/* login */}
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />
          <Route path="/forgot-password" element={<ForgotPassword />} />

          {/* dept */}
          <Route path="/dept" element={<DeptList />} />
          <Route path="/add-dept" element={<AddDept />} />
          <Route path="/dept/:dno" element={<Dept />} />

          {/* emp(연습) */}
          <Route path="/emp" element={<EmpList />} />
          <Route path="/add-emp" element={<AddEmp />} />
          <Route path="/emp/:eno" element={<Emp />} />

          {/* qna */}
          <Route path="/qna" element={<QnaList />} />
          <Route path="/add-qna" element={<AddQna />} />
          <Route path="/qna/:qno" element={<Qna />} />

          {/* customer */}
          <Route path="/customer" element={<CustomerList />} />
          <Route path="/add-customer" element={<AddCustomer />} />
          <Route path="/customer/:cid" element={<Customer />} />

          {/* faq */}
          <Route path="/faq" element={<FaqList />} />
          <Route path="/add-faq" element={<AddFaq />} />
          <Route path="/faq/:no" element={<Faq />} />

          {/* cinema faq */}
          <Route path="/cinema-faq" element={<CinemaFaqList />} />
          <Route path="/add-cinema-faq" element={<AddCinemaFaq />} />
          <Route path="/cinema-faq/:cfno" element={<CinemaFaq />} />

          {/* reply-board */}
          <Route path="/reply-board" element={<ReplyBoardList />} />
          <Route path="/add-reply-board" element={<AddReplyBoard />} />
          {/* 정리 : boardParent = 0 이면 부모글을 클릭 */}
          {/* 정리 : boardParent = 0 아니면 자식글을 클릭 */}
          <Route
            path="/reply-board/bid/:bid/boardParent/:boardParent"
            element={<ReplyBoard />}
          />

          {/* thread-board */}
          <Route path="/thread-board" element={<ThreadBoardList />} />
          <Route path="/add-thread-board" element={<AddThreadBoard />} />
          <Route
            path="/thread-board/tid/:tid/tparent/:tparent"
            element={<ThreadBoard />}
          />

          {/* codeCategory(대분류 공통코드(부모)) */}
          <Route path="/code-category" element={<CodeCategoryList />} />
          <Route path="/add-code-category" element={<AddCodeCategory />} />

          {/* code(소분류 공통코드(자식)) */}
          <Route path="/code" element={<CodeList />} />
          <Route path="/add-code" element={<AddCode />} />
          <Route path="/code/:codeId" element={<Code />} />

          {/* simple-product */}
          <Route path="/simple-product" element={<SimpleProductList />} />
          <Route path="/add-simple-product" element={<AddSimpleProduct />} />
          <Route path="/simple-product/:spno" element={<SimpleProduct />} />
          {/* 장바구니 상세 */}
          <Route path="/simple-cart/:spno" element={<SimpleCart />} />
          {/* 장바구니 전체 조회 */}
          <Route path="/simple-cart" element={<SimpleCartList />} />

          {/* product(연습) */}
          <Route path="/product" element={<ProductList />} />
          <Route path="/add-product" element={<AddProduct />} />
          <Route path="/product/:pno" element={<Product />} />

          {/* cinema */}
          {/* 박스오피스 순위 전체조회 */}
          <Route path="/cinema" element={<CinemaList />} />
          {/* 영화 상세조회 */}
          <Route path="/cinema/:movieCd" element={<Cinema />} />

          {/* 부산 테마길( busan thema load ) */}
          <Route path="/thema-load" element={<ThemaLoadList />} />
         
          {/* 파일 업로드 */}
          <Route path="/fileDb" element={<FileDbList />} />

          {/* NotFound */}
          <Route path="*" element={<NotFound />} />
        </Routes>
        {/* 라우터 정의 끝 */}
      </div>
    </div>
  );
}

export default App;

공공데이터 포털 회원가입

https://www.data.go.kr/

 

공공데이터 포털

국가에서 보유하고 있는 다양한 데이터를『공공데이터의 제공 및 이용 활성화에 관한 법률(제11956호)』에 따라 개방하여 국민들이 보다 쉽고 용이하게 공유•활용할 수 있도록 공공데이터(Datase

www.data.go.kr

 

부산관광공사_음식테마거리 음식점 이미지정보 검색

 

 

활용 신청


src - types - shop - IThemaLoad.ts 생성

 IThemaLoad.ts

// IThemaLoad.ts : rfce
export default interface IThemaLoad {
    "식당(ID)": number;      // 식당 ID
    "식당명": string;           // 식당명
    "지역명": string;           // 식당명
    "식당이미지(ID)": number;  // 식당이미지(ID)
    "식당이미지(URL)": string; // 식당이미지(URL)
  }

 

src - services -shop - ThemaLoadService.ts 생성

 

ThemaLoadService.ts

// ThemaLoadService.ts : 공공 데이터 포털 API 함수

import axios from "axios";
import IThemaLoad from './../../types/shop/IThemaLoad';

// 공공 데이터 포털 : 부산 테마거리 음식점 기본 주소

// 인증키 변수
let apiKey = "JYF5IjHIFxh5YyspCWG8zcRMgGfWLsqno9aGODy8haDoXpFUe7FqKgp2LwtlRcxjkbMcbZ06ejs5oUj1DO389A%3D%3D";

// 전체 조회
// page : 현재페이지번호,
// perPage : 1페이지당 개수
const getAll = (page: number, perPage:number) => {
    // url 조합 : 기본주소 + 추가주소 + 변수명(쿼리스트링)
    let url = `${baseUrl}/15096718/v1/uddi:0a31f303-432c-4993-97d2-81537862521b?page=${page}&perPage=${perPage}&serviceKey=${apiKey}`;
    console.log(url);

    return axios.get<Array<IThemaLoad>>(url);

 }

 const ThemaLoadService = {
    getAll,
 };

 export default ThemaLoadService;

 

결과