TIL

5월 30일 TIL - (개인프로젝트) api로 받아온 정보를 html에 넣기

양죠니 2023. 5. 30. 23:28

개인프로젝트를 진행하던 중

1. 영화정보 api를 받아와서

2. 필요한 정보만 빼내 객체로 만들고

3. 배열에다가 넣으려고 했다

 

3번까지 잘 했지만 배열에서 인덱스 값으로 내부 정보를 빼려고 하니 undifined가 나왔다

class movieCard { // title(제목), overview(내용 요약), poster_path(포스터 이미지 경로), vote_average(평점), id(영화식별값) 
	constructor(title, overview, poster_path, vote_average, id) { 
    this.title = title; 
    this.overview = overview; 
    this.poster_path = poster_path; 
    this.vote_average = vote_average; 
    this.id = id; 
    } 
}

우선 api에서 받아올 정보를 담을 class 객체를 만들었고

 

movies = []; 
fetch( "https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1", options ) 
.then((response) => response.json()) 
.then((response) => { 
	let arr = response.results; 
    arr.forEach((a) => { 
    //forEach 돌면서 받아온 api 데이터 중 유의미한 값들만 뽑아오기 
    let title = a["title"]; 
    let overview = a["overview"]; 
    let poster_path = a["poster_path"]; 
    let vote_average = a["vote_average"]; 
    let id = a["id"]; 
    
    //class사용해서 각 영화의 정보들을 인스턴스로 만들어주기 
    let movieInfo = new movieCard( title, overview, poster_path, vote_average, id ); 
    movies.push(movieInfo); 
    }); }) 
    .catch((err) => console.error(err));

api에서 받아온 정보들을 arr에 담아 forEach를 돌면서 class에 담을 정보들을 뽑았다.

뽑은 정보들을 변수에 저장하고 객체에 넣어 인스턴스화 시켜주고 movies 배열에 push 해줬다.

 

 fetch 함수 밖에서 console.log(movies)를 해주면 해당 데이터들이 잘 담겨있었지만 movies[0] 이런식으로 배열의 인덱스 값으로 출력을 해보면 undefined 가 떠버렸다. 알음알음 구글링을 해보니 api를 받아오고 데이터를 데이터베이스에 넣기 전에 console.log를 해버린 것 같은 느낌..! 

async/await을 썼는데도 똑같아서 그냥 fetch문 안에 html을 추가해주었다.

 

const cardWrapper = document.getElementById("card-wrapper");

fetch(
  "https://api.themoviedb.org/3/movie/top_rated?language=en-US&page=1",
  options
)
  .then((response) => response.json())
  .then((response) => {
    let arr = response.results;
    console.log(arr);

    arr.forEach((a) => {
      let title = a["title"];
      let overview = a["overview"];
      let poster_path = a["poster_path"];
      let vote_average = a["vote_average"];
      let id = a["id"];

      console.log(poster_path);

      let temp_html = `<div class="card">
                              <img src="https://image.tmdb.org/t/p/w200${poster_path}" alt="" />
                              <h3 id="title">${title}</h3>
                              <p id="score">score: ${vote_average}</p>
                              <p id="explanation">${overview}</p>
                          </div>`;

      cardWrapper.innerHTML += temp_html;
    });
  })
  .catch((err) => console.error(err));

나중에 검색기능으로 영화의 id값을 alert로 띄워야 해서 데이터들을 fetch에서 빼고싶었는데 ,,, 일단 우선 이렇게 구현을 했다.

temp_html 에 벡틱으로 html 코드를 작성해 감싸주고 getElemtById로 뽑아온 컨테이너 div를 cardWrapper로 지정해 innerHTML로 추가했다. 

 

나름 써보니 짧지만 오늘 하루종일 한 것... 내일 검색기능도 구현해야함 ㅠ ,ㅋ