첫째주 #4 React 기초 - API , github pages

김선은·2023년 5월 18일

github pages 설치하기

  • 만든 html, css, javascript로 웹사이트로 만들어줌
  1. npm i gh-pages 로 설치한다
    2. npm run build 명령어 입력 => 코드 압축, 최적화한 build 폴더 생김
  2. package.json 에서 "scripts": 내부에 deploy와 predeploy 추가
  "scripts": {
    "deploy": "gh-pages -d build", // gh-pages 실행
    "predeploy" : "npm run build" // deploy 실행 시키면 자동으로 먼저 실행됨
  },
  1. package.json 맨 아래에 코드 추가
{
, "homepage": "http://깃허브 유저 네임.github.io/깃허브 저장소 이름"
}
  1. npm run deploy

혹시 React router 6버전으로 진행시 gh-pages로 배포 후, 빈 화면이 나온다면 Route컴포넌트의 path경로 앞에 process.env.PUBLIC_URL을 추가해서 수정하기

Route path={`${process.env.PUBLIC_URL}/`} element={< Home />}

ex) path={`${process.env.PUBLIC_URL}/movie/:id`}

movie api로 영화 정보 보여주기

  1. useState() 만들기
  2. getAPI 함수를 async await 함수로 만들어서 fetch("url").json()
  3. 1번 함수에 setState로 json.data.원하는정보 넣기.
  4. useEffect에 getAPI 함수 넣어주기 (api 한번만 불러오게끔)
  5. 1번 함수 값을 가져와서 map 돌려서 보여주기
function Home() {
  const [loading, setLoading] = useState(true);
  const [movies, setMovies] = useState([]);
  const getMoives = async () => {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json?minimum_rating=8.5&sort_by=year");
    const json = await response.json();
    setMovies(json.data.movies);
    setLoading(false);
  };
  
  useEffect(() => {
    getMoives();
  }, []);
  
  return (
      <div>
        {loading ? (
          <h1>Loading...</h1>
        ) : (
          <div>
            {movies.map((item) => ( //Movie Component 따로 있음
              <Movie
                id={item.id}
                key={item.id}
                coverImg={item.medium_cover_image}
                title={item.title}
                summary={item.summary}
                genres={item.genres}
              />
            ))}
          </div>
        )}
      </div>
  );

API 정보! fetch, async await

헷갈릴 땐 자주 봐야지

  1. fetch 함수를 만들어서 react-query에 전달
function fetchCoins() {
  return fetch("url").then((response) => response.json());
}
  1. async await
const getMoives = async () => {
    const response = await fetch("url");
    const json = await response.json();
  };
// async 사용하는 함수 만들고 useEffect 안에 넣기
useEffect(() => {
  getMoives();
}, []);
profile
기록은 기억이 된다

0개의 댓글