본문 바로가기
TIL

Plmography 프로젝트 작업 로그 #19 - api 로 유튜브 영상 불러오기 (22.12.31 TIL)

by winteringg 2022. 12. 31.

상세 페이지에서 유튜브 링크 불러오기 작업을 진행한 오늘.. db 에 저장된 tmdbId 값을 가져오고, 그 아이디값을 프론트에서 호출하는 api 에 넣어주어서 유튜브 링크를 화면에 출력했다. 

일단 apiStore 를 만들어서 api 호출문을 저장해줌.

// apiStore

async fetchVideo(tmdbId) {
    const apiBaseUrl = apiConfig.tmdbApiUrl;

    const apiKey = apiConfig.key;

    this.videoUrl = await (
      await fetch(`${apiBaseUrl}/movie/${tmdbId}/videos?api_key=${apiKey}&language=ko-KR`)
    ).json();

    this.publish();
  }

그런데 db 에서 호출되는 tmdbId 가 중간에 undefined 가 되는 상황이 발생해서, 컴포넌트에서 tmdbId 가 존재하는 경우에만 useEffect 가 발동되도록 해주었는데 이게 맞는지는 잘 모르겠지만 일단 작동은 된다.

// component

export default function ContentDetail() {
  const {
    tmdbId, korTitle, engTitle, imageUrl,
    releaseDate, platform, description,
  } = content;

  const youtubeStore = useYoutubeStore();

  const { videoUrl } = youtubeStore;
  
  useEffect(() => {
    if (tmdbId) {
      youtubeStore.fetchVideo(tmdbId);
    }
  }, [tmdbId]);

    return(
        <div>
          {videoUrl && videoUrl.results.length > 0
            ? (
              <iframe
                title="video"
                src={`https://www.youtube.com/embed/${videoUrl.results[0].key}?autoplay=0&mute=1&loop=0`}
                width="420"
                height="280"
              />
            )
            : (
              <p>영상이 존재하지 않습니다.</p>
            )}
        </div>
}

작동되는 화면! 일단 동작되는 건 확인했으니 다시 리팩토링 하러 총총,,,

댓글