use-popular-posts.ts
1 import { useEffect, useState } from 'react'; 2 import { Subplebbit } from '@plebbit/plebbit-react-hooks'; 3 import { getCommentMediaInfo, getHasThumbnail } from '../lib/utils/media-utils'; 4 5 const usePopularPosts = (subplebbits: Subplebbit[]) => { 6 const [popularPosts, setPopularPosts] = useState<Comment[]>([]); 7 const [isLoading, setIsLoading] = useState(true); 8 const [error, setError] = useState<string | null>(null); 9 10 useEffect(() => { 11 const fetchPopularPosts = () => { 12 try { 13 setIsLoading(true); 14 setError(null); 15 const uniqueLinks: Set<string> = new Set(); 16 const allPosts: Comment[] = []; 17 18 const postsPerSub = [0, 8, 4, 3, 2, 2, 2, 2, 1][Math.min(subplebbits.length, 8)]; 19 20 subplebbits.forEach((subplebbit: any) => { 21 let subplebbitPosts: Comment[] = []; 22 23 if (subplebbit?.posts?.pages?.hot?.comments) { 24 for (const post of Object.values(subplebbit.posts.pages.hot.comments as Comment)) { 25 const { deleted, link, locked, pinned, removed, replyCount, timestamp } = post; 26 27 try { 28 const commentMediaInfo = getCommentMediaInfo(post); 29 const hasThumbnail = getHasThumbnail(commentMediaInfo, link); 30 31 if ( 32 hasThumbnail && 33 (replyCount > 0 || postsPerSub > 1) && 34 !deleted && 35 !removed && 36 !locked && 37 !pinned && 38 timestamp > Date.now() / 1000 - 60 * 60 * 24 * 30 && 39 !uniqueLinks.has(link) 40 ) { 41 subplebbitPosts.push(post); 42 uniqueLinks.add(link); 43 } 44 } catch (err) { 45 console.error('Error processing post:', err); 46 } 47 } 48 49 subplebbitPosts.sort((a: any, b: any) => b.timestamp - a.timestamp); 50 allPosts.push(...subplebbitPosts.slice(0, postsPerSub)); 51 } 52 }); 53 54 const sortedPosts = allPosts.sort((a: any, b: any) => b.timestamp - a.timestamp).slice(0, 8); 55 56 setPopularPosts(sortedPosts); 57 } catch (err) { 58 console.error('Error in usePopularPosts:', err); 59 setError('Failed to fetch popular posts'); 60 } finally { 61 setIsLoading(false); 62 } 63 }; 64 65 fetchPopularPosts(); 66 }, [subplebbits]); 67 68 return { popularPosts, isLoading, error }; 69 }; 70 71 export default usePopularPosts;