For Programmer

7. 디테일 비디오 페이지에 사이드 비디오 리스트 생성 - 유튜브 클론 코딩 본문

React & Node.js 프로젝트/유튜브 클론 코딩

7. 디테일 비디오 페이지에 사이드 비디오 리스트 생성 - 유튜브 클론 코딩

유지광이 2020. 7. 23. 18:59
728x90

1. Components - views - VIdeoDetailPage - Sections - SideVideo.js 만들기

2. SideVideo.js 코딩(Axios통신으로 서버에 동영상 리스트 받기까지 포함)

import React, { useEffect, useState } from 'react';
import Axios from 'axios';

function SideVideo() {
  const [sideVideos, setsideVideos] = useState([]);

  useEffect(() => {
    Axios.get('/api/video/getVideos').then((response) => {
      if (response.data.success) {
        console.log(response.data);
        setsideVideos(response.data.videos);
      } else {
        alert('비디오 가져오기를 실패했습니다.');
      }
    });
  }, []);

  const renderSideVideo = sideVideos.map((video, index) => {
    var minutes = Math.floor(video.duration / 60);
    var seconds = Math.floor(video.duration - minutes * 60);
    return (
      <div
        key={index}
        style={{ display: 'flex', marginBottom: '1rem', padding: '0 2rem' }}
      >
        <div style={{ width: '40%', marginRight: '1rem' }}>
          <a href={`/video/${video._id}`}>
            <img
              style={{ width: '100%', height: '100%' }}
              src={`http://localhost:5000/${video.thumbnail}`}
              alt="thumbnail"
            />
          </a>
        </div>

        <div style={{ width: '50%' }}>
          <a href={`/video/${video._id}`} style={{ color: 'gray' }}>
            <span style={{ fontSize: '1rem', color: 'black' }}>
              {video.title}
            </span>
            <br />
            <span>{video.writer.name}</span>
            <br />
            <span>{video.views} views</span>
            <br />
            <span>
              {minutes} : {seconds}
            </span>
            <br />
          </a>
        </div>
      </div>
    );
  });
  return (
    <React.Fragment>
      <div style={{ marginTop: '3rem' }}>{renderSideVideo}</div>
    </React.Fragment>
  );
}

export default SideVideo;

3. 서버에서 Axios요청에 응답하여 동영상 데이터 보내주기(LandingPage에서 사용했던 코드 재사용)

router.get("/getVideos", (req, res) => {
  //비디오를 DB에서 가져와서 클라이언트에 보낸다.
  Video.find() //Video collection에있는 모든 데이터들을 찾는다.
    .populate("writer") //writer에 type으로 Schema.Types.ObjectId라고 지정을 해주었었는데 populate를 걸어줘야 user에있는 모든 데이터들을 들고올 수있다.
    //populate를 안걸어 줄 경우 writer의 id만 가져온다.
    .exec((err, videos) => {
      if (err) return res.status(400).send(err);
      res.status(200).json({ success: true, videos });
    });
});

4. 실행결과

 

해당강의

 

728x90
Comments