보라코딩

리액트 공공데이터 API 가져오기 본문

코딩/REACT

리액트 공공데이터 API 가져오기

new 보라 2023. 8. 20. 10:14

 

 

공공데이터 포털

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

www.data.go.kr

 

 

 

import React from "react";
import axios from "axios";
import { useState, useEffect } from "react";

export default function Api() {
  const URL =

  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = async () => {
    try {
      setError(null);
      setData(null);
      setLoading(true);

      const response = await axios.get(URL, {
        params: {
          serviceKey:
            "개인키 넣기~~~~~~~~~~~~",
          pageNo: 1,
          numOfRows: 1000,
          dataType: "JSON",
          base_date: "20230820",
          base_time: "0600",
          nx: 55,
          ny: 127,
        },
      });

      setData(response.data);
    } catch (e) {
      setError(e);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  if (!data) return null;

  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}