mirror of
https://github.com/bitsocialnet/5chan.git
synced 2026-08-03 07:41:04 +02:00
fix(hooks): fix usePopularPosts loading state and change detection
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
import { useMemo, useRef } from 'react';
|
import { useMemo, useRef } from 'react';
|
||||||
import { Subplebbit } from '@plebbit/plebbit-react-hooks';
|
import { Comment, Subplebbit } from '@plebbit/plebbit-react-hooks';
|
||||||
import { getCommentMediaInfo, getHasThumbnail } from '../lib/utils/media-utils';
|
import { getCommentMediaInfo, getHasThumbnail } from '../lib/utils/media-utils';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -51,17 +51,20 @@ const usePopularPosts = (subplebbits: Subplebbit[]) => {
|
|||||||
}
|
}
|
||||||
}, [subplebbits]);
|
}, [subplebbits]);
|
||||||
|
|
||||||
// Create stable reference: only update if the CIDs actually change
|
// Create stable reference: only update if the post content actually changes
|
||||||
// This prevents unnecessary rerenders when only updatingState changes
|
// Build a key from relevant mutable fields, not just CIDs
|
||||||
const currentCids = popularPosts.map((p: any) => p.cid).join(',');
|
const currentKey = popularPosts.map((p) => `${p.cid}:${p.replyCount}:${p.timestamp}:${p.locked}:${p.pinned}`).join(',');
|
||||||
const stablePostsRef = useRef<Comment[]>(popularPosts);
|
const stablePostsRef = useRef<Comment[]>(popularPosts);
|
||||||
|
|
||||||
if (currentCids !== prevCidsRef.current) {
|
if (currentKey !== prevCidsRef.current) {
|
||||||
prevCidsRef.current = currentCids;
|
prevCidsRef.current = currentKey;
|
||||||
stablePostsRef.current = popularPosts;
|
stablePostsRef.current = popularPosts;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isLoading = stablePostsRef.current.length === 0;
|
// Derive loading state from subplebbit states rather than post count
|
||||||
|
// A subplebbit is still loading if it has no posts pages yet and isn't in a terminal state
|
||||||
|
const hasLoadedData = subplebbits.some((sub) => sub?.posts?.pages?.hot?.comments);
|
||||||
|
const isLoading = subplebbits.length > 0 && !hasLoadedData;
|
||||||
|
|
||||||
return { popularPosts: stablePostsRef.current, isLoading, error };
|
return { popularPosts: stablePostsRef.current, isLoading, error };
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user