Fetching Movies from API

2021. 7. 3. 02:41Big Dreamer_Developer/React

일반적으로 javascript에서 data를 fetch하는 방법은 fetch()를 사용하는 것이다. 하지만 더 좋은 방법이 있는데, 바로 Axiod이다.  

좋다, 우리는 axios를 사용할 것인데, 왜냐면 많이 사용되고 좋은 방법이기 때문이다. axios는 매우 쉬운 개념인데, 마치 fetch 위에 있는 작은 layer(층)라고 개념을 잡으면 편하다. 예를 들어서, axios는 땅콩 주위를 감싸고 있는 멋진 초콜릿이라고 생각하면 쉽다. 하지만 axios를 사용하려면, 우선 우리는 axios를 설치해야한다. 설치하는 방법은 매우 쉽다.

npm i axios

위 코드를 터미널에 입력하면 끝이다. 

 

이제 우리가 쓸 API에 대해서 알아보자. 우리는 YTS에서 만든 API를 사용할 것이다.

 

우선 axios를 import해준 다음,

https://yts-proxy.now.sh/list_movies.json

위 링크를 이용해 다음과 같이 API를 설정한다.

import React from 'react';
import axios from 'axios';

class App extends React.Component {
  state = {
    isLoding: true,
    movies: [],
  };
  componentDidMount() {
    axios.get('https://yts.mx/api/v2/list_movies.json');
  }
  render() {
    const { isLoding } = this.state;
    return <div>{isLoding ? 'Loading...' : 'We are ready'}</div>;
  }
}

export default App;

 

 

그 다음 우리가 해야할 일은 axios로부터 온 data를 잡아야 한다. axios가 위 링크를 들어가면 보이는 것처럼 우리에게 정보를 제공하지만, 우리는 그 데이터를 잡아야지만 우리의 state에 사용할 수 있다. 그래서 우리가 할 일은 다음과 같다.

import React from 'react';
import axios from 'axios';

class App extends React.Component {
  state = {
    isLoding: true,
    movies: [],
  };
  getMovies = async () => {
    const movies = await axios.get('https://yts.mx/api/v2/list_movies.json');
  };
  componentDidMount() {
    this.getMovies();
  }
  render() {
    const { isLoding } = this.state;
    return <div>{isLoding ? 'Loading...' : 'We are ready'}</div>;
  }
}

export default App;

 코드를 처음부터 끝까지 살펴보고 복습을 하며 위 코드에서 우리가 추가한 내용에 대해서 이해해보자.

우선 application은 render한다. 처음에는 isLoading은 true이고 그래서 페이지에는 시각적으로 Loading...이 보일 것이다. 그 후 이제 application이 mount된 후, 우리는 getMovies function을 호출할 것이다. 그리고 getMovies는 axios.get을 사용하지만 axios.get은 완료되기까지 시간이 좀 필요하기 때문에 await를 넣었고, await는 단독으로 사용하는 것이 아니라 async와 함께 이용되기때문에 async 키워드도 넣어주었다. async와 await를 하는 것은 기본적으로 Javascript에게 getMovies function에게 조금 시간이 필요하고 우리는 그걸 기다려야만 한다는 것을 말해주는 것이다. 만약 우리가 async와 await 키워드를 사용하지 않는다면 Javascript는 function을 기다려주지 않을 것이다. 그리고 우린 다른 방법으로 해결하기 위해서 더 많은 코드가 필요할 것이다. 그래서 이 경우에는 awync await를 써야한다. 이제 우리는 접근이 끝날때까지 기다릴 것이다.  

'Big Dreamer_Developer > React' 카테고리의 다른 글

About the Router  (0) 2021.07.06
Rendering The Movies  (0) 2021.07.03
Planning the Movie Component  (0) 2021.07.03
Component Life Cycle  (0) 2021.07.03
Protection with PropTypes & defaultProps  (0) 2021.07.01