fetch API는 Promise의 형식으로 이루어져 있습니다.
fetch(url)
.then((response) => response.json())
// 자체적으로 json() 메소드가 있어, 응답을 JSON 형태로 변환시켜서 다음 Promise로 전달합니다
.then((json) => console.log(json))
// 콘솔에 json을 출력합니다
.catch((error) => console.log(error));
// 에러가 발생한 경우, 에러를 띄웁니다
//API 가져올때 3단계
//1. useEffect안에 바로 fetch사용하기
useEffect(()=>{
fetch("https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year")
.then((response)=>response.json())
.then((json)=>setMovies(json))
}, [])
//2. async & await를 활용해서 가져오기
const getMoives = async() => {
const response = await fetch("https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year");
const json = await response.json();
setMovies(json.data.movies);
setLoading(false);
}
//2-1. 좀 더 축약한 코드
const getMoives = async() => {
const json = await (
await fetch("https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year")
).json();
setMovies(json.data.movies);
setLoading(false);
}