JavaScript/React

React Axios로 API에서 받아온 데이터 확인 # 4.1. Rendering the Movies

Codezoy 2020. 6. 29. 18:23
이 글은, 노마드코더의 "ReactJS로 영화 웹 서비스 만들기"를 공부한 내용을 수강자 입장에서 필기한 것으로, 
다소 불친절한 설명이 있을 수 있음을 미리 알립니다.

초기코드

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;

API에서 받아온 데이터 확인

getMovies = async () => {
    const movies = await axios.get("https://yts-proxy.now.sh/list_movies.json");
    console.log(movies);
  };

  • movies만 가져오는 것이 목표 → 다음과 같이 코드 수정 (방법1)
getMovies = async () => {
    const movies = await axios.get("https://yts-proxy.now.sh/list_movies.json");
    console.log(movies.data.data.movies);
  };
  • 결과

(방법2)

getMovies = async () => {
    const {data: {data: {movies}}} = await axios.get("https://yts-proxy.now.sh/list_movies.json");
    console.log(movies);
  };
  • 결과

State의 movies List에 데이터 삽입

getMovies = async () => {
    const {
      data: {
        data: { movies },
      },
    } = await axios.get("https://yts-proxy.now.sh/list_movies.json");

// ## 데이터 삽입 ## //
    this.setState({ movies, isLoading: false }); // this.setState({ movies:movies, ... });
  };

State가 필요 없으면, class component가 될 필요가 없다.

function component로 충분함.

Movie.js

import React from "react";
import PropTypes from "prop-types";
function Movie({ id, year, title, summary, poster }) {
  return <h4>{title}</h4>;
}
Movie.propTypes = {
  id: PropTypes.number.isRequired,
  year: PropTypes.number.isRequired,
  title: PropTypes.string.isRequired,
  summary: PropTypes.string.isRequired,
  poster: PropTypes.string.isRequired,
};
export default Movie;

App.js

import React from "react";
import axios from "axios";
import Movie from "./Movie";

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?sort_by=rating");
    this.setState({ movies, isLoading: false }); // this.setState({ movies:movies, ... });
  };
  componentDidMount() {
    this.getMovies();
  }
  render() {
    const { isLoading, movies } = this.state;
    return (
      <div>
        {isLoading
          ? "Loading.."
          : movies.map((movie) => {
              return <Movie        // Movie 함수 사용
              key={movie.id} 
              id={movie.id} 
              year={movie.year} 
              title={movie.title} 
              summary={movie.summary} 
              poster={movie.medium_cover_image} 
              />;
            })}
      </div>
    );
  }
}

export default App;