diff --git a/src/hooks/use-comment-media-info.ts b/src/hooks/use-comment-media-info.ts index 3a724b30..02a99527 100644 --- a/src/hooks/use-comment-media-info.ts +++ b/src/hooks/use-comment-media-info.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect } from 'react'; import { useLocation, useParams } from 'react-router-dom'; import { Comment } from '@plebbit/plebbit-react-hooks'; import { getCommentMediaInfo, fetchWebpageThumbnailIfNeeded } from '../lib/utils/media-utils'; @@ -9,36 +9,35 @@ export const useCommentMediaInfo = (comment: Comment) => { const params = useParams(); const isInPostPageView = isPostPageView(location.pathname, params); const isInPendingPostView = isPendingPostView(location.pathname, params); + // some sites have CORS access, so the thumbnail can be fetched client-side, which is helpful if subplebbit.settings.fetchThumbnailUrls is false - const initialCommentMediaInfo = useMemo(() => getCommentMediaInfo(comment), [comment]); - const [commentMediaInfo, setCommentMediaInfo] = useState(initialCommentMediaInfo); - const fetchThumbnail = useCallback(async () => { - if (!isInPostPageView && !isInPendingPostView) { - return; // don't fetch in feed view, it displaces the posts - } - if (initialCommentMediaInfo?.type === 'webpage' && !initialCommentMediaInfo.thumbnail) { - const newMediaInfo = await fetchWebpageThumbnailIfNeeded(initialCommentMediaInfo); - + let commentMediaInfo = getCommentMediaInfo(comment); + if (commentMediaInfo?.type === 'webpage' && !commentMediaInfo.thumbnail) { + const newMediaInfo = await fetchWebpageThumbnailIfNeeded(commentMediaInfo); // Fetch the dimensions of the thumbnail if (newMediaInfo.thumbnail) { const img = new Image(); img.onload = () => { - setCommentMediaInfo({ + commentMediaInfo = { ...newMediaInfo, thumbnailWidth: img.width, thumbnailHeight: img.height, - }); + }; }; img.src = newMediaInfo.thumbnail; - } else { - setCommentMediaInfo(newMediaInfo); } + commentMediaInfo = newMediaInfo; } - }, [initialCommentMediaInfo, isInPostPageView, isInPendingPostView]); - useEffect(() => { - fetchThumbnail(); - }, [fetchThumbnail]); + return commentMediaInfo; + }, [comment]); - return commentMediaInfo; + useEffect(() => { + // don't fetch in feed view, it displaces the posts + if (isInPostPageView && isInPendingPostView) { + fetchThumbnail(); + } + }, [fetchThumbnail, isInPostPageView, isInPendingPostView]); + + return getCommentMediaInfo(comment); };