Skip to content

Commit

Permalink
refactor: useFetchVideoTitle가 useQuery를 사용하도록 수정(#160)
Browse files Browse the repository at this point in the history
- 동영상 타이틀이 랜더링되는 속도가 향상되어 비디오 제목이 unknown으로 최대한 나오지 않게함.
- useQuery를 사용하여 동일한 fetch를 여러번 하지 않고 캐싱을 함.
- fetchYouTubeVideoData에서 try-catch문을 사용하여 reponse.data()시의 에러도 로깅하도록함.
- 에러 로그에 status HTTP 상태 코드를 넣어 더 나오는 에러로깅을 하도록함.
  • Loading branch information
nakyeonko3 committed Sep 12, 2024
1 parent 01abc50 commit 3b0e3a9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 30 deletions.
33 changes: 19 additions & 14 deletions src/api/fetchYouTubeVideoData.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
export const fetchYouTubeVideoData = async (videoId: string) => {
const apiKey = import.meta.env.VITE_YOUTUBE_API_KEY;
const response = await fetch(
`https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=${videoId}&key=${apiKey}`,
);
try {
const response = await fetch(
`https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=${videoId}&key=${apiKey}`,
);

if (!response.ok) {
throw new Error('비디오 정보를 가져오는데 실패했습니다.');
}
if (!response.ok) {
throw new Error('비디오 정보를 가져오는데 실패했습니다. status:' + response.status);
}

const data = await response.json();
const videoDetails = data.items[0];
const data = await response.json();
const videoDetails = data.items[0];

return {
title: videoDetails.snippet.title,
creator: videoDetails.snippet.channelTitle,
uploadDate: videoDetails.snippet.publishedAt,
views: videoDetails.statistics.viewCount,
};
return {
title: videoDetails.snippet.title,
creator: videoDetails.snippet.channelTitle,
uploadDate: videoDetails.snippet.publishedAt,
views: videoDetails.statistics.viewCount,
};
} catch (error) {
console.error(error);
throw new Error('비디오 정보를 가져오는데 실패했습니다.');
}
};
26 changes: 10 additions & 16 deletions src/hooks/useFetchVideoTitle.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';

import { fetchYouTubeVideoData } from '@/api/fetchYouTubeVideoData';
import { extractVideoId } from '@/utils/youtubeUtils';

export const useFetchVideoTitle = (videoUrl: string) => {
const [videoTitle, setVideoTitle] = useState<string>('');

useEffect(() => {
const fetchVideoTitle = async () => {
const { data, isError, isLoading } = useQuery({
queryKey: ['videoTitle', videoUrl],
queryFn: async () => {
const videoId = extractVideoId(videoUrl);
if (videoId) {
const videoData = await fetchYouTubeVideoData(videoId);
setVideoTitle(videoData.title);
return await fetchYouTubeVideoData(videoId);
} else {
console.error('Invalid video URL');
setVideoTitle('유효하지 않은 비디오 URL');
}
};

if (videoUrl) {
fetchVideoTitle();
}
}, [videoUrl]);

return videoTitle;
},
});
if (isLoading) return '';
if (isError) return '';
return data?.title || '';
};

0 comments on commit 3b0e3a9

Please sign in to comment.