본문 바로가기
JavaScript/React

[React] #4.0 Fetching Movies from API (#코딩공부)

by 함께 공부해요 2020. 6. 2.

https://youtu.be/bfUC2Iy6jt4


<복습>

https://wook-2124.tistory.com/135

 

[React] #3.3 Planning the Movie Component (#코딩공부)

https://youtu.be/rwQf12jN_hw <복습> https://wook-2124.tistory.com/134 https://wook-2124.tistory.com/133 [React] #3.1 All you need to know about State (#코딩공부) https://youtu.be/38I5K3p42WU <복습>..

wook-2124.tistory.com

 

<준비물>

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com


1. axios

axios는 마치 fetch 위에 있는 작은 layer(계층)이다. 더 쉽게 설명하면, 땅콩(fetch)를 둘러싸고 있는 초콜릿(axios)라고 할 수 있다.


2. API

YTX(토렌트 사이트)에서 Movies List API를 가져와보자. 여기서 HTTP GET, Endpoint(종단 간 종단, Transport 4계층)에 해당하는 json URL을 복사하면 되는데, YTX에서 API를 매번 업데이트 하면서 URL이 바뀌기 때문에 다른 API를 사용해야 된다.

 

때문에 니꼬가 URL이 변동되지 않는 YTX proxy API를 만들었으므로 이 API를 쓰면된다.

 

https://github.com/serranoarevalo/yts-proxy

 

serranoarevalo/yts-proxy

YTS REST API Proxy Serverless Function. Contribute to serranoarevalo/yts-proxy development by creating an account on GitHub.

github.com

 

설치한 axios를 import(수입)하고, render(표현)이 된 후 실행되는 componentDidMount에 axios.get("니꼬's API")data fetch(가져)와보자.

 

isLoading = true로 인해 "Loading..."이 render(표현)되고, componentDidMount에 의해서 axios가 list_movies.json을 Request URL로써 가져오는 것을 알 수 있다.


3. async

axios가 data를 GET(fetch)하는데엔 시간이 조금 걸리니, getMovies로 async(비동기) 설정을 하고 axios가 "니꼬's API"를 get(fetch)해오는 것을 await(기다)리게 했다. 그리고 componentDidMount에서 this.getMovies로 호출했다.

 

정리하자면 Application을 render(표현)하는데 isLoading의 condition(조건)이 true(참)이므로, 처음 localhost 화면에 "Loading..."이 render(표현)된 후, componentDidMount에 의해 getMovies가 실행된다.

 

하지만 axios가 "니꼬's API(data)"를 get(fetch)해오는데에는 시간이 좀 걸리기 때문에, await을 써서 JavaScript가 기다려야한다는 것을 알게 해줘야 하는데, async(비동기) function으로 이것을 해결할 수 있다.

댓글