From 35a3b697233cd78db70ea2832b889f789fcd3d98 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Fri, 2 Oct 2026 17:38:17 +0300 Subject: [PATCH] Refresh the forked Home's feeds with one fetch and one write (#11842) Co-authored-by: Claude Opus 5.5 (1M context) --- src/features/followingV2/home/FeedPage.tsx | 21 +- src/features/followingV2/home/PostFeed.tsx | 110 ++++-- .../home/queries/postFeed.test.tsx | 372 +++++++++++++++++- .../followingV2/home/queries/postFeed.ts | 115 +++++- 4 files changed, 565 insertions(+), 53 deletions(-) diff --git a/src/features/followingV2/home/FeedPage.tsx b/src/features/followingV2/home/FeedPage.tsx index d17eb9e87..64a0cc218 100644 --- a/src/features/followingV2/home/FeedPage.tsx +++ b/src/features/followingV2/home/FeedPage.tsx @@ -10,7 +10,6 @@ import {View} from 'react-native' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {type NavigationProp, useNavigation} from '@react-navigation/native' -import {useQueryClient} from '@tanstack/react-query' import {DISCOVER_FEED_URI, VIDEO_FEED_URIS} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -20,7 +19,6 @@ import {listenSoftReset} from '#/state/events' import {FeedFeedbackProvider, useFeedFeedback} from '#/state/feed-feedback' import {useSetHomeBadge} from '#/state/home-badge' import {type FeedSourceInfo} from '#/state/queries/feed' -import {truncateAndInvalidate} from '#/state/queries/util' import {useSession} from '#/state/session' import {FAB} from '#/view/com/util/fab/FAB' import {type ListMethods} from '#/view/com/util/List' @@ -36,12 +34,8 @@ import { isFollowingV2HomeDotEnabled, } from '#/features/followingV2/eligibility' import {app} from '#/lexicons' -import {PostFeed} from './PostFeed' -import { - type FeedDescriptor, - type FeedParams, - RQKEY as FEED_RQKEY, -} from './queries/postFeed' +import {PostFeed, type PostFeedRef} from './PostFeed' +import {type FeedDescriptor, type FeedParams} from './queries/postFeed' const POLL_FREQ = 60e3 // 60sec @@ -70,12 +64,12 @@ export function FeedPage({ const {hasSession} = useSession() const {_} = useLingui() const navigation = useNavigation>() - const queryClient = useQueryClient() const {openComposer} = useOpenComposer() const [isScrolledDown, setIsScrolledDown] = useState(false) const headerOffset = useHeaderOffset() const feedFeedback = useFeedFeedback(feedInfo, hasSession) const scrollElRef = useRef(null) + const feedRef = useRef(null) const [hasNew, setHasNew] = useState(false) const setHomeBadge = useSetHomeBadge() const isVideoFeed = useMemo(() => { @@ -107,7 +101,7 @@ export function FeedPage({ TabState.InsideAtRoot if (isScreenFocused && isPageFocused) { scrollToTop() - void truncateAndInvalidate(queryClient, FEED_RQKEY(feed)) + void feedRef.current?.refresh() setHasNew(false) ax.metric('feed:refresh', { feedType: feed.split('|')[0], @@ -115,7 +109,7 @@ export function FeedPage({ reason: 'soft-reset', }) } - }, [ax, navigation, isPageFocused, scrollToTop, queryClient, feed]) + }, [ax, navigation, isPageFocused, scrollToTop, feed]) // fires when page within screen is activated/deactivated useEffect(() => { @@ -131,14 +125,14 @@ export function FeedPage({ const onPressLoadLatest = useCallback(() => { scrollToTop() - void truncateAndInvalidate(queryClient, FEED_RQKEY(feed)) + void feedRef.current?.refresh() setHasNew(false) ax.metric('feed:refresh', { feedType: feed.split('|')[0], feedUrl: feed, reason: 'load-latest', }) - }, [ax, scrollToTop, feed, queryClient]) + }, [ax, scrollToTop, feed]) const shouldPrefetch = IS_NATIVE && isPageAdjacent const isDiscoverFeed = feedInfo.uri === DISCOVER_FEED_URI @@ -164,6 +158,7 @@ export function FeedPage({ headerOffset={headerOffset} savedFeedConfig={savedFeedConfig} isVideoFeed={isVideoFeed} + ref={feedRef} /> diff --git a/src/features/followingV2/home/PostFeed.tsx b/src/features/followingV2/home/PostFeed.tsx index 8af4313a6..092afc1a3 100644 --- a/src/features/followingV2/home/PostFeed.tsx +++ b/src/features/followingV2/home/PostFeed.tsx @@ -26,7 +26,7 @@ import {DISCOVER_FEED_URI, KNOWN_SHUTDOWN_FEEDS} from '#/lib/constants' import {useBottomBarOffset} from '#/lib/hooks/useBottomBarOffset' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' -import {isNetworkError} from '#/lib/strings/errors' +import {cleanError, isNetworkError} from '#/lib/strings/errors' import {logger} from '#/logger' import {usePostAuthorShadowFilter} from '#/state/cache/profile-shadow' import {listenPostCreated} from '#/state/events' @@ -44,6 +44,7 @@ import {PostFeedErrorMessage} from '#/view/com/posts/PostFeedErrorMessage' import {PostFeedItem} from '#/view/com/posts/PostFeedItem' import {ShowLessFollowup} from '#/view/com/posts/ShowLessFollowup' import {ViewFullThread} from '#/view/com/posts/ViewFullThread' +import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' import {List, type ListRef} from '#/view/com/util/List' import {PostFeedLoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' import {LoadMoreRetryBtn} from '#/view/com/util/LoadMoreRetryBtn' @@ -83,6 +84,7 @@ import { RQKEY, usePostFeedFetcher, usePostFeedQuery, + usePostFeedRefresh, } from './queries/postFeed' import {useSavedFeedSamples} from './queries/savedFeedSamples' @@ -103,6 +105,11 @@ type FeedRow = type: 'loadMoreError' key: string } + | { + type: 'refreshError' + key: string + error: Error + } | { type: 'feedShutdownMsg' key: string @@ -197,7 +204,8 @@ export function getItemsForFeedback(feedRow: FeedRow): { } export type PostFeedRef = { - refreshFeed: () => Promise + /** Refreshes the feed in one write. Callers log their own metric. */ + refresh: () => Promise } // DISABLED need to check if this is causing random feed refreshes -prf @@ -303,12 +311,16 @@ let PostFeed = ({ isFetched, isError, error, - refetch, hasNextPage, isFetchingNextPage, fetchNextPage, } = usePostFeedQuery(feed, feedParams, opts) const {createFeedApi} = usePostFeedFetcher(feed) + const { + refresh, + error: refreshError, + isRefreshing, + } = usePostFeedRefresh(feed, feedParams) const samples = useSavedFeedSamples({ enabled: enabled !== false && feed === 'following', pages: feedData?.pages, @@ -330,7 +342,14 @@ let PostFeed = ({ }, [lastFetchedAt]) const checkForNew = useNonReactiveCallback(async () => { - if (!data?.pages[0] || isFetching || !onHasNew || !enabled || disablePoll) { + if ( + !data?.pages[0] || + isFetching || + isRefreshing || + !onHasNew || + !enabled || + disablePoll + ) { return } @@ -342,7 +361,7 @@ let PostFeed = ({ try { if (await pollLatest(data.pages[0], createFeedApi())) { if (isEmpty) { - void refetch() + void refresh() } else { onHasNew(true) } @@ -371,9 +390,18 @@ let PostFeed = ({ (feed === 'following' || feed === `author|${myDid}|posts_and_author_threads`) ) { - void queryClient.invalidateQueries({queryKey: RQKEY(feed)}) + /* + * A disabled feed isn't shown, so it can refetch once it's enabled. + * Truncating first means that refetch is one page, not every page it + * had loaded. + */ + if (enabled) { + void refresh() + } else { + void truncateAndInvalidate(queryClient, RQKEY(feed)) + } } - }, [queryClient, feed, myDid]) + }, [queryClient, feed, myDid, enabled, refresh]) useEffect(() => { return listenPostCreated(onPostCreated) }, [onPostCreated]) @@ -432,6 +460,12 @@ let PostFeed = ({ feed.startsWith('author|') ? undefined : data?.pages, ) + /** + * A refresh leaves the query's own error in place, so while one retries an + * errored empty feed, the loading row stands in for the error row. + */ + const isRetryingError = isRefreshing && isError && isEmpty + const feedItems: FeedRow[] = useMemo(() => { // wraps a slice item, and replaces it with a showLessFollowup item // if the user has pressed show less on it @@ -466,7 +500,7 @@ let PostFeed = ({ key: 'feedShutdownMsg', }) } - if (isFetched) { + if (isFetched && !isRetryingError) { if (isError && isEmpty) { arr.push({ type: 'error', @@ -725,8 +759,22 @@ let PostFeed = ({ }) } + /* + * A failed refresh keeps the posts it failed to replace, so its error goes + * above them. An errored empty feed shows it in its error row instead. + */ + if (refreshError && !(isError && isEmpty)) { + arr.unshift({ + type: 'refreshError', + key: 'refreshError', + error: refreshError, + }) + } + return arr }, [ + refreshError, + isRetryingError, description, isFetched, isError, @@ -754,33 +802,21 @@ let PostFeed = ({ // = // - const refreshFeed = async () => { - if (!enabled) return - - ax.metric('feed:refresh', { - feedType: feedType, - feedUrl: feed, - reason: 'pull-to-refresh', - }) - try { - await truncateAndInvalidate(queryClient, RQKEY(feed, feedParams)) - if (onHasNew) { - onHasNew(false) - } - } catch (err) { - logger.error('Failed to refresh posts feed', {message: err}) - } - } - const onRefresh = async () => { setIsPTRing(true) - await refreshFeed() + if (enabled) { + ax.metric('feed:refresh', { + feedType: feedType, + feedUrl: feed, + reason: 'pull-to-refresh', + }) + await refresh() + onHasNew?.(false) + } setIsPTRing(false) } - useImperativeHandle(ref, () => ({ - refreshFeed, - })) + useImperativeHandle(ref, () => ({refresh})) const onEndReached = useCallback(async () => { if (isFetching || !hasNextPage || isError) return @@ -807,9 +843,9 @@ let PostFeed = ({ ]) const onPressTryAgain = useCallback(() => { - void refetch() + void refresh() onHasNew?.(false) - }, [refetch, onHasNew]) + }, [refresh, onHasNew]) const onPressRetryLoadMore = useCallback(() => { void fetchNextPage() @@ -826,11 +862,18 @@ let PostFeed = ({ return ( ) + } else if (row.type === 'refreshError') { + return ( + + ) } else if (row.type === 'loadMoreError') { return ( ({ @@ -59,10 +61,12 @@ const mockModerationOpts = { prefs: DEFAULT_LOGGED_OUT_PREFERENCES.moderationPrefs, labelDefs: {}, } -let mockPreferences: { - savedFeeds: {pinned: boolean; value: string}[] - interests: {tags: string[]} -} +let mockPreferences: + | { + savedFeeds: {pinned: boolean; value: string}[] + interests: {tags: string[]} + } + | undefined const DISCOVER = PROD_DEFAULT_FEED('whats-hot') const CUSTOM = 'at://did:plc:author/app.bsky.feed.generator/custom' @@ -80,7 +84,7 @@ const mockClient = { ( method: unknown, params: {feed?: string; cursor?: string; limit: number}, - ) => { + ): unknown => { const endpoint = endpointOf(method, params) if (params.limit === 1) { return {feed: [feedItem(`${endpoint}-latest`)]} @@ -211,7 +215,10 @@ function setDev(value: boolean) { /** Pins Following first, which makes the Following feed Home. */ function pinFollowingFirst() { - mockPreferences.savedFeeds = [{pinned: true, value: 'following'}] + mockPreferences = { + savedFeeds: [{pinned: true, value: 'following'}], + interests: {tags: []}, + } } describe('post-feed query data', () => { @@ -359,6 +366,359 @@ describe('pollLatest', () => { }) }) +describe('usePostFeedRefresh', () => { + const KEY = RQKEY('following') + + async function renderRefreshableFeed() { + const queryClient = createQueryClient() + const wrapper = ({children}: PropsWithChildren) => ( + {children} + ) + /** The data of every render, to count the renders a write causes. */ + const rendered: unknown[] = [] + const hook = renderHook( + () => { + const query = usePostFeedQuery('following') + // Read as PostFeed does, so that a change to it alone renders too. + void query.isFetching + rendered.push(query.data) + return {query, ...usePostFeedRefresh('following')} + }, + {wrapper}, + ) + await waitFor(() => expect(hook.result.current.query.isSuccess).toBe(true)) + mockClient.call.mockClear() + const data = () => + queryClient.getQueryData>(KEY) + return {hook, queryClient, rendered, data} + } + + /** Every write of the query's data from here on. */ + function watchWrites(queryClient: QueryClient) { + const writes: unknown[] = [] + queryClient.getQueryCache().subscribe(event => { + if (event.type === 'updated' && event.action.type === 'success') { + writes.push(event.query.state.data) + } + }) + return writes + } + + /** Holds the next request until the test answers it. */ + function holdNextRequest() { + let resolve!: (value: unknown) => void + let reject!: (error: unknown) => void + mockClient.call.mockImplementationOnce( + () => + new Promise((res, rej) => { + resolve = res + reject = rej + }), + ) + return { + respond: (rkey: string) => + resolve({cursor: 'timeline:1', feed: [feedItem(rkey)]}), + fail: (error: Error) => reject(error), + } + } + + function failNextRequest(error: Error) { + mockClient.call.mockImplementationOnce(() => Promise.reject(error)) + } + + /** Lets TanStack deliver the notifications it has scheduled. */ + function flushNotifications() { + return act(() => new Promise(resolve => setTimeout(resolve, 0))) + } + + function topPostUri(data?: InfiniteData) { + return data?.pages[0]?.feed[0]?.post.uri + } + + it('writes the new top page once, in one render, and paginates from it', async () => { + const {hook, queryClient, rendered, data} = await renderRefreshableFeed() + await act(() => hook.result.current.query.fetchNextPage()) + const writes = watchWrites(queryClient) + const rendersBefore = rendered.length + mockClient.call.mockReturnValueOnce({ + cursor: 'timeline:1', + feed: [feedItem('fresh')], + }) + + await act(() => hook.result.current.refresh()) + await flushNotifications() + + expect(writes).toHaveLength(1) + expect(data()?.pageParams).toEqual([undefined]) + expect(topPostUri(data())).toBe(feedItem('fresh').post.uri) + const dataChanges = rendered + .slice(rendersBefore) + .filter( + (d, i, all) => d !== (i ? all[i - 1] : rendered[rendersBefore - 1]), + ) + expect(dataChanges).toHaveLength(1) + + mockClient.call.mockClear() + await act(() => hook.result.current.query.fetchNextPage()) + expect(requested()).toEqual(['timeline timeline:1']) + }) + + it('keeps the pages and their pagination when the refresh fails', async () => { + const {hook, queryClient, data} = await renderRefreshableFeed() + const before = data() + const writes = watchWrites(queryClient) + failNextRequest(new Error('offline')) + + await act(() => hook.result.current.refresh()) + + expect(hook.result.current.error?.message).toBe('offline') + expect(writes).toHaveLength(0) + expect(data()).toBe(before) + expect(hook.result.current.query.isError).toBe(false) + await act(() => hook.result.current.query.fetchNextPage()) + expect(requested()).toEqual(['timeline undefined', 'timeline timeline:1']) + }) + + it('clears the error while a refresh is pending, and restores it if that fails', async () => { + const {hook} = await renderRefreshableFeed() + const state = () => hook.result.current + failNextRequest(new Error('offline')) + await act(() => hook.result.current.refresh()) + + const retry = holdNextRequest() + let retrying!: Promise + act(() => { + retrying = hook.result.current.refresh() + }) + expect(state().error).toBeUndefined() + expect(state().isRefreshing).toBe(true) + + await act(async () => { + retry.fail(new Error('still offline')) + await retrying + }) + expect(state().error?.message).toBe('still offline') + expect(state().isRefreshing).toBe(false) + + await act(() => hook.result.current.refresh()) + expect(state().error).toBeUndefined() + }) + + it('logs unexpected errors but not network ones', async () => { + const logError = jest.spyOn(logger, 'error').mockImplementation(() => {}) + try { + const {hook} = await renderRefreshableFeed() + failNextRequest(new TypeError('Network request failed')) + await act(() => hook.result.current.refresh()) + expect(hook.result.current.error).toBeDefined() + expect(logError).not.toHaveBeenCalled() + + failNextRequest(new Error('Unexpected')) + await act(() => hook.result.current.refresh()) + expect(logError).toHaveBeenCalledTimes(1) + } finally { + logError.mockRestore() + } + }) + + it('joins a refresh already in flight', async () => { + const {hook, queryClient} = await renderRefreshableFeed() + const writes = watchWrites(queryClient) + const top = holdNextRequest() + + let first!: Promise + let second!: Promise + act(() => { + first = hook.result.current.refresh() + second = hook.result.current.refresh() + }) + await act(async () => { + top.respond('fresh') + await Promise.all([first, second]) + }) + + expect(second).toBe(first) + expect(requested()).toEqual(['timeline undefined']) + expect(writes).toHaveLength(1) + }) + + it('cancels a fetchNextPage still in flight, and drops its page', async () => { + const {hook, queryClient, data} = await renderRefreshableFeed() + const next = holdNextRequest() + let fetchingNextPage!: Promise + act(() => { + fetchingNextPage = hook.result.current.query.fetchNextPage() + }) + const writes = watchWrites(queryClient) + mockClient.call.mockReturnValueOnce({ + cursor: 'timeline:1', + feed: [feedItem('fresh')], + }) + + await act(() => hook.result.current.refresh()) + await act(async () => { + next.respond('late') + await fetchingNextPage + }) + + expect(writes).toHaveLength(1) + expect(data()?.pages).toHaveLength(1) + expect(topPostUri(data())).toBe(feedItem('fresh').post.uri) + expect(hook.result.current.query.isFetchingNextPage).toBe(false) + }) + + it('still writes after a page load lands while it is in flight', async () => { + const {hook, data} = await renderRefreshableFeed() + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + await act(() => hook.result.current.query.fetchNextPage()) + expect(data()?.pages).toHaveLength(2) + + await act(async () => { + top.respond('fresh') + await refreshing + }) + + expect(data()?.pages).toHaveLength(1) + expect(topPostUri(data())).toBe(feedItem('fresh').post.uri) + }) + + describe('gives way to TanStack', () => { + it('when a refetch has replaced the top page', async () => { + const {hook, data} = await renderRefreshableFeed() + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + await act(() => hook.result.current.query.refetch()) + const refetched = data() + + await act(async () => { + top.respond('fresh') + await refreshing + }) + + expect(data()).toBe(refetched) + }) + + it('when a refetch from the top is still in flight', async () => { + const {hook, queryClient, data} = await renderRefreshableFeed() + const top = holdNextRequest() + const refetch = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + void hook.result.current.query.refetch() + }) + const writes = watchWrites(queryClient) + + await act(async () => { + top.respond('fresh') + await refreshing + }) + expect(writes).toHaveLength(0) + + await act(async () => { + refetch.respond('refetched') + await waitFor(() => expect(writes).toHaveLength(1)) + }) + expect(topPostUri(data())).toBe(feedItem('refetched').post.uri) + }) + + it('when the feed is reset', async () => { + const {hook, queryClient, data} = await renderRefreshableFeed() + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + await act(() => queryClient.resetQueries({queryKey: KEY})) + + await act(async () => { + top.respond('fresh') + await refreshing + }) + + expect(topPostUri(data())).toBe(feedItem('timeline-1').post.uri) + }) + + it('when the feed is removed', async () => { + const {hook, queryClient, data} = await renderRefreshableFeed() + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + act(() => { + queryClient.removeQueries({queryKey: KEY}) + }) + + await act(async () => { + top.respond('fresh') + await refreshing + }) + + expect(topPostUri(data())).not.toBe(feedItem('fresh').post.uri) + }) + }) + + it('reports nothing when it fails after the feed has moved on', async () => { + const {hook} = await renderRefreshableFeed() + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + await act(() => hook.result.current.query.refetch()) + + await act(async () => { + top.fail(new Error('offline')) + await refreshing + }) + + expect(hook.result.current.error).toBeUndefined() + expect(hook.result.current.isRefreshing).toBe(false) + }) + + it('still commits when it finishes after the view unmounts', async () => { + const {hook, queryClient, data} = await renderRefreshableFeed() + const writes = watchWrites(queryClient) + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + hook.unmount() + + await act(async () => { + top.respond('fresh') + await refreshing + }) + + expect(writes).toHaveLength(1) + expect(topPostUri(data())).toBe(feedItem('fresh').post.uri) + }) + + it('does nothing before the first load has settled', async () => { + mockPreferences = undefined + const queryClient = createQueryClient() + const wrapper = ({children}: PropsWithChildren) => ( + {children} + ) + const hook = renderHook(() => usePostFeedRefresh('following'), {wrapper}) + renderHook(() => usePostFeedQuery('following'), {wrapper}) + + await act(() => hook.result.current.refresh()) + + expect(requested()).toEqual([]) + expect(queryClient.getQueryData(KEY)).toBeUndefined() + }) +}) + describe('RQKEY', () => { const custom: FeedDescriptor = `feedgen|${CUSTOM}` diff --git a/src/features/followingV2/home/queries/postFeed.ts b/src/features/followingV2/home/queries/postFeed.ts index ce5107f4b..497e469e2 100644 --- a/src/features/followingV2/home/queries/postFeed.ts +++ b/src/features/followingV2/home/queries/postFeed.ts @@ -1,4 +1,4 @@ -import {useCallback, useMemo, useRef} from 'react' +import {useCallback, useMemo, useRef, useState} from 'react' import {AppState} from 'react-native' import {type Client} from '@atproto/lex' import {type AtIdentifierString, type AtUriString} from '@atproto/syntax' @@ -10,8 +10,10 @@ import { } from '@bsky/sdk/moderation' import { type InfiniteData, + type QueryClient, type QueryKey, useInfiniteQuery, + useQueryClient, } from '@tanstack/react-query' import {AuthorFeedAPI} from '#/lib/api/feed/author' @@ -25,6 +27,7 @@ import { type FeedViewPostsSlice, } from '#/lib/api/feed-manip' import {DISCOVER_FEED_URI} from '#/lib/constants' +import {isNetworkError} from '#/lib/strings/errors' import {logger} from '#/logger' import {useFeedTuners} from '#/state/preferences/feed-tuners' import {useModerationOpts} from '#/state/preferences/moderation-opts' @@ -424,6 +427,116 @@ export function usePostFeedFetcher(feedDesc: FeedDescriptor) { return {createFeedApi, fetchPage} } +type PostFeedData = InfiniteData + +/** + * Refreshes the feed from the top with one fetch and then one write, so the + * new top renders once and a failed refresh leaves the feed as it was. `error` + * is why the last refresh failed, cleared when another starts. Refetches from + * an invalidation or a reset still go through TanStack. + * + * One started while another is pending joins it. One that finishes after the + * view has gone still commits, which is safe, as the commit gives way to + * anything that has replaced the top page since. + */ +export function usePostFeedRefresh( + feedDesc: FeedDescriptor, + params?: FeedParams, +) { + const queryClient = useQueryClient() + const {fetchPage} = usePostFeedFetcher(feedDesc) + const queryKey = RQKEY(feedDesc, params) + const [error, setError] = useState(undefined) + const [isRefreshing, setIsRefreshing] = useState(false) + /** The pending refresh, for another to join. */ + const pending = useRef>(undefined) + + const refreshFromTop = async () => { + const before = queryClient.getQueryData(queryKey) + setError(undefined) + setIsRefreshing(true) + try { + const page = await fetchPage(undefined) + await commit(queryClient, queryKey, before, { + pages: [page], + pageParams: [undefined], + }) + } catch (e) { + if (!isNetworkError(e)) { + logger.error('Failed to refresh posts feed', {safeMessage: e}) + } + // Nothing to report once the feed has moved on. + if (!isTopReplaced(queryClient, queryKey, before)) { + setError(e instanceof Error ? e : new Error(String(e))) + } + } finally { + pending.current = undefined + setIsRefreshing(false) + } + } + + const refresh = () => { + /* + * Until the first load settles there's nothing to refresh, and the query + * may still be waiting for the preferences it fetches with. + */ + const status = queryClient.getQueryState(queryKey)?.status + if (!status || status === 'pending') { + return Promise.resolve() + } + pending.current ??= refreshFromTop() + return pending.current + } + + return {refresh, error, isRefreshing} +} + +/** Whether something else has replaced the feed's top page since `before`. */ +function isTopReplaced( + queryClient: QueryClient, + queryKey: QueryKey, + before: PostFeedData | undefined, +) { + return ( + queryClient.getQueryData(queryKey)?.pages[0] !== + before?.pages[0] + ) +} + +/** + * Writes `data` over the feed's, unless something else has replaced its top + * page since `before` was read (a refetch, a reset or a removal) or is + * fetching it now. + */ +async function commit( + queryClient: QueryClient, + queryKey: QueryKey, + before: PostFeedData | undefined, + data: PostFeedData, +) { + const state = queryClient.getQueryState(queryKey) + // A fetch from the top in flight will land after this write, so it wins. + const isFetchingTop = + state?.fetchStatus !== 'idle' && !state?.fetchMeta?.fetchMore + if (isTopReplaced(queryClient, queryKey, before) || isFetchingTop) { + return + } + /* + * A fetchNextPage in flight would land after this write and put back the + * pages it replaces, so it's cancelled. Cancelling reverts its state at + * once, and waiting for it lets one that had already resolved write first. + * Anything fetching after that started since, from the data being replaced. + */ + await queryClient.cancelQueries({queryKey, exact: true}) + if ( + isTopReplaced(queryClient, queryKey, before) || + queryClient.getQueryState(queryKey)?.fetchStatus !== 'idle' + ) { + return + } + queryClient.setQueryData(queryKey, data) +} + /** * Whether the feed has a newer post than its top `page` has seen. `api` should * be a fresh one from {@link usePostFeedFetcher}. -- knotmirror 0.0.1