꾸준히 성장하는 개발자

[React] API를 이용한 data 가져오기 본문

React

[React] API를 이용한 data 가져오기

ahleum 2022. 5. 12. 15:19

1. then() 을 사용한 방법

 
 useEffect(() => {
    fetch(
      `https://yts.mx/api/v2/list_movies.json?minimum_rating=8.8&sort_by=year`
    )
      .then((response) => response.json())
      .then((json) => {
        setMovies(json.data.movies);
        setLoading(false); //로딩이 끝났으니 finish시켜주기 위해 진행
      });
  }, []);
 
 
 
 
 
 

2. async await 사용한 방법

 
 
const getMovies = async () => {
    const response = await fetch(
      `https://yts.mx/api/v2/list_movies.json?minimum_rating=8.8&sort_by=year`
    );
    const json = await response.json();
    setMovies(json.data.movies);
    setLoading(false);
  };
  useEffect(() => {
    getMovies();
  }, []);

 

 

 

 
 

 3. 좀 더 짧게 하는 방법

 
const getMovies = async () => {
    const json = await (
      await fetch(
        `https://yts.mx/api/v2/list_movies.json?minimum_rating=8.8&sort_by=year`
      )
    ).json();
    setMovies(json.data.movies);
    setLoading(false);
  };
  useEffect(() => {
    getMovies();
  }, []);
  console.log(movies);