No.5 ReactJS로 영화 웹 서비스 만들기

Jetom·2021년 8월 14일
0

react

목록 보기
5/15
post-thumbnail

😀 만들었던 코드를 이제 지운뒤, movie component를 이제 시작하겠다 !!

Planning the Movie Component

우선 mount를 해야하는데, 이것은 태어나는 것 이라고 생각하면 된다.

class App extends Component{
  //mount되면 loding은 기본적으로 true!
  state = {
  	isLoading: true
  };

  render(){
    const {isLoading} = this.state;
    return <div>
      {/*js의 삼항연산자를 이용한다.*/}
      {isLoading ? "Loading": "ready"}
    </div>;
  }
 }

componentDidMount는 component가 mount되자 마자 호출이 되는데,
componentDidMount에 setTimeout을 사용하여 딜레이를 주어 바로 loading을 나타내기보다 시간을 주고 loading이라는 문자열을 나타내보자!

class App extends Component{
  //mount되면 loding은 기본적으로 true!
  state = {
  	isLoading: true
  };

//setTimeout은 delay function이다.(6초 후에 ready로 바뀜)
  componentDidMount() {
    setTimeout(() => { this.setState({ isLoading: false })}, 6000)
  }

  render(){
    const {isLoading} = this.state;
    return <div>
      {/*js의 삼항연산자를 이용한다.*/}
      {isLoading ? "Loading": "ready"}
    </div>;
  }
 }

componentDidMount에서 setTimeout을 해준 이유는 data를 fetch하는 이유 때문인데 API에서 data fetching이 완료되면 ready대신 movie를 render하고 map을 만들고 movie를 render하는 것!
(한마디로 API를 가져와서 ready대신 movie list를 보여준다는 뜻 같다.🙄)

setState를 사용할 때 state 안에 default 값을 선언할 필요는 없고, state는 선택 사항이지만 state를 사용할것 같을 때 미리 선언할 필요는 없다!(사라질 수도 있는 state이기 때문에)

Fetching Movies from API

일반적으로 javascript에서 data를 fetch로 사용하는데, 니콜라스가 선택한 방법은 axios를 사용하는것이다. axios는 fetch 위에 있는 layer라고 한다. (사실 무슨 뜻인지 이해가 가지않아 axios에 관한 내용을 정리해야겠다 생각한다...😥)

axios는 다음과 같은 명령어로 설치한다!

npm i axios

API는 YTS(불법 토렌트 영화 사이트)를 쓰는데, 여기서 봐야할것은 list movie이고 JSON을 예쁘게 정렬하려면 JSON view라는 확장 기능을 사용하자
그럼 아래와 같은 사진처럼 예쁘게 나타나는것을 볼 수 있다!

https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh/related?hl=ko&hc_location=ufi

JSON을 살펴보니 movie는 큰 object인데 그곳엔 하나의 movie, 또 다른 movie 계속해서 movie가 있는것을 볼 수 있다. (마치 food array를 만들었을 때 처럼!)

YTS는 불법 사이트기 때문에 API는 변하고 URL이 변경되서 니콜라스가 YTS proxy API를 만들었다고하니 https://yts-proxy.now.sh/list_movies.json로 넣자!

  //이제 didmount에 url을 입력해보자
  componentDidMount() {
    axios.get("https://yts-proxy.now.sh/list_movies.json");
  }

axios로 API를 받아오고 새로고침을 했는데 loading만 뜨는것을 볼 수 있는데, 이때 우리는 받아온 date를 잡은 뒤 state에 사용 할 수 있다.(가져오는걸 보려면 network에서 list_movies.json을 확인해보자)

axios.get은 항상 빠르지 않는데 그 때를 위해 javascript에게 componentDidMount 함수가 끝날 때 까지 기다리라고 말해야한다.


class App extends Component {
  state = {
    isLoading: true
  };

//이 함수는 비동기로서 async를 통해 getMovies를 기다리라 말하는것과 같다.
 getMovies = async () => {
   //await는 어떤것을 기다리기 원하냐라고 묻는것과 같다.
   const movies = await axios.get("https://yts-proxy.now.sh/list_movies.json")
 }

  componentDidMount() {
	this.getMovies();
  }
  render() {
    const { isLoading } = this.state;
    return <div>
      {isLoading ? "Loading" : "ready"}
    </div>;
  }
}

🙈 쓰고나니까 async, await, axios를 또 공부해야겠다는 생각이 들었다.....

profile
사람이 좋은 인간 리트리버 신혜리입니다🐶

0개의 댓글