본문 바로가기
Front end/React 따라하기1

5) 리액트에서 API 요청하기 SWR

by 구월에작은섬 2020. 7. 17.
donaricano-btn

자, 이제 리액트에서 API를 요청하기 위한 준비를 해보겠다.

 

일반적으로 리액트에서 많이 쓰이는 Ajax API 통신용라이브러리는

 

1.브라우저에 내장된 window.fetch

 

2. Axios

 

3. Jquery Ajax등이 있다.

 

이번에 나는 React hooks에 최적화됐다는 SWR이라는 녀석을 써보기로 한다.

 

https://swr.vercel.app/

 

SWR: React Hooks for Data Fetching

SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

swr.vercel.app

 

먼저 설치부터 해보자

yarn add swr

 

문서를 조금 훑어 보니 어째 Axios보다 조금 더 귀찮은 느낌이다.

 

하지만 Auto Revalidation이나 Get데이터 호출에 특화되어있기 때문에 POST같은 기능을 수행하지않는

 

단순 SPA에 쓰기에는 좋을것 같다. 

 

글을 쓰는 지금은 밤늦은 시간이어서 아직 데이터가 없으니 어제자 날짜로 한번 날려보도록한다.

 

src/component/Main.js를 아래처럼 수정해보자

 

import React, { useState, useEffect } from "react";
import * as dateFns from "date-fns";
import useSWR from "swr";

const host = "covid-193.p.rapidapi.com";
const key = 발급받은 키를 입력하세요

const fetcher = (url) =>
  fetch(url, {
    method: "GET",
    headers: {
      "x-rapidapi-host": host,
      "x-rapidapi-key": key,
      useQueryString: true,
    },
  }).then((res) => res.json());
const index = () => {
  let today = new Date();
  let yesterday = dateFns.format(
    today.setDate(today.getDate() - 1),
    "yyyy-MM-dd"
  );
  //데이터 건수
  let url =
    "https://covid-193.p.rapidapi.com/history?country=S-Korea&day=" + yesterday;
  const { data, error } = useSWR(url, fetcher);
  if (error) return "에러발생";
  if (!data) return "로딩중..";
  console.log(data);
  return (
    <div>
      {data.results}건의 데이터가 있습니다.
      <br />
      <div>
        {data.response.map((item, index) => (
          <div key={index}>
            <p>신규발생:{item.cases.new}명</p>
            <p>확진:{item.cases.active}명</p>
            <p>위독:{item.cases.critical}명</p>
            <p>회복:{item.cases.recovered}명</p>
            <p>전체 감염자수:{item.cases.total}명</p>
            <p>
              측정날짜 :{" "}
              {dateFns.format(new Date(item.time), "yyyy년MM월dd일 HH시mm분")}
            </p>
            <br />
          </div>
        ))}
      </div>
    </div>
  );
};

export default index;

 

결과물

donaricano-btn

댓글