본문 바로가기
카테고리 없음

6. 리액트 영화 앱 만들기

by 닉우 2020. 8. 5.

<영화 API 사용해 보기>

 

여기서는 fetch() 대신에 axios라는 도구를 사용하겠다.

 

axios 설치


YTS라는 곳에서 제공하는 영화 데이터 API를 사용할거다.

 

저걸 사용할거다.

API 는 식당 점원같은 역할을 한다.

프로그램들이 서로 상호작용하는 것을 도와주는 매개체로 볼 수 있다.

 

결국 API란 두 시스템,

어플리케이션이 상호작용(소통) 할 수 있게 하는 프로토콜의 총 집합이라면

ENDPOINT란 API가 서버에서 리소스에 접근할 수 있도록 가능하게 하는 URL이다.

 


영화 정보를 더 자세하게 보여주는 API는 movie_id라는 조건을 요구한다.


App.js 파일 맨 위에 axios를 import한 다음, componentDidMount() 함수에서 axios로 API를 호출하면 된다.

class App extends React.Component {
  state = {
    isLoading: true,
    movies: [],
  };
  componentDidMount() {
    axios.get('https://yts-proxy.now.sh/list_movies.json');
  }

 


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

class App extends React.Component {
	state = {
		isLoading: true,
		movies: []
	};
	getMovies = async () => {
		const movies = await axios.get('https://yts-proxy.now.sh/list_movies.json');
		console.log(movies);
	};
	componentDidMount() {
		this.getMovies();
	}

	render() {
		const { isLoading } = this.state;
		return <div> {isLoading ? 'Loading...' : 'We are ready'} </div>;
	}
}

export default App;

 

 

axios.get을 사용해서 영화 정보를 불러와 빈 배열인 movies에 넣어줬다.

async, await은 영화 정보를 불러올때 시간이 걸리므로 자바스크립트에게 미리 알려주는것이다.

 

영화들이 id별로 배열에 나열된것을 볼 수 있다. data -> data -> movies 순서대로 객체에 접근하면 데이터를 추출할 수 있다.


<movies state에 데이터 저장하기>

 

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

class App extends React.Component {
	state = {
		isLoading: true,
		movies: []
	};
	getMovies = async () => {
		const { data: { data: { movies } } } = await axios.get('https://yts-proxy.now.sh/list_movies.json');
		this.setState({ movies, isLoading: false });
	};
	componentDidMount() {
		this.getMovies();
	}

	render() {
		const { isLoading } = this.state;
		return <div> {isLoading ? 'Loading...' : 'We are ready'} </div>;
	}
}

export default App;

 

this.setState({movies : movies}) 에서 키와 대입할 변수의 이름이 같으니까 this.setState({movies})로 수정한거다.

 


 

 

댓글