2022. 9. 22. 17:45ㆍReact/ReactJS로 영화 웹 서비스 만들기
일반적으로 javascript에서 data를 fetch하는 방법은 fetch를 사용하는 것이다.
근데 더 획기적인 방법 axios가 있다!!
자 그럼 한번 설치해보자.
npm install axios
YTS에서 만든 API를 사용해보자.
우리는 역서 API를 가지고 올거다.
우리는 그중 ListMovies를 사용할 것이다.
https://yts.mx/api/v2/list_movies.json
우선 json파일이 나올텐데 크롬의 json viewer라는 extension을 사용하면 좋다.
https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh/related?hl=ko
근데 얘네는 불법이라.. 니코쌤이 멋지게 proxy로 만들어주셨다넹
https://yts-proxy.nomadcoders1.now.sh/list_movies.json
https://yts-proxy.now.sh/list_movies.json
https://github.com/serranoarevalo/yts-proxy
자 그럼 axios를 import하고 사용해보자.
import React from "react";
import axios from "axios";
class App extends React.Component {
state = {
isLoading: true,
movies: [],
};
componentDidMount() {
axios.get("https://yts-proxy.nomadcoders1.now.sh/list_movies.json");
}
render() {
const { isLoading } = this.state;
return <div>{this.state.isLoading ? "Loading..." : "We are ready"}</div>;
}
}
export default App;
자 그래서 inspection쪽으로 가서 refresh하면 Loading이라고 뜨고
axios는 보다시피 뭔가 요청하고 있는것을 볼 수 있다 네트워크에 있는것이다!
우리는 data를 잡아야하기때문에, 그래야 state에 사용할 수 있기때문에
const movies로 잡아보겠다.
axios.get은 빠르지 않기때문에 기다려보자.
componentDidMount함수가 끝날때까지 약간 시간이 걸릴 수 있기에 기다려야한다.
그래서 우리는 componentDidMount앞에 async를 넣을것이다.
그래서 component가 mount되면 우리는 getMovie를 호출할것이다.
axios가 끝날때까지 기다렸다가 계속하도록!
복습해보자!
Application은 render한다.
처음에는 isLoading:true
다음에 application이 mount된 후
getMovies funtion호출
getMovies는 axios.get을 사용 - 하지만 axios.get은 완료되기까지 시간이 조금 필요하기 때문에 await를 넣음
근데 다음과 같이 async를 사용하지않으면 await를 사용할 수 없다고 한다.
자 그럼 async를 넣어주고
async, awiat은 우리가 기본적으로 javascript에게 getMovies function에게 조금 시간이 필요하고 우리는 그걸 기다려야만 한다는것을 말하는것이다.
'React > ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글
12.2 Styling the Movies (0) | 2022.09.23 |
---|---|
12.1 Rendering the Movies (2) | 2022.09.23 |
11.3 Planning the Movie Component (0) | 2022.09.22 |
11.2 Component Life Cycle (0) | 2022.09.22 |
11.1 All you need to know about State (2) | 2022.09.22 |