diff --git a/src/api/fetchYouTubeVideoData.ts b/src/api/fetchYouTubeVideoData.ts index e60d135..72c9c05 100644 --- a/src/api/fetchYouTubeVideoData.ts +++ b/src/api/fetchYouTubeVideoData.ts @@ -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('비디오 정보를 가져오는데 실패했습니다.'); + } }; diff --git a/src/hooks/useFetchVideoTitle.ts b/src/hooks/useFetchVideoTitle.ts index 2743092..a282176 100644 --- a/src/hooks/useFetchVideoTitle.ts +++ b/src/hooks/useFetchVideoTitle.ts @@ -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(''); - - 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 || ''; };