From e57f4be16d83e0771c643b13789a272e4a877c3b Mon Sep 17 00:00:00 2001 From: Michele De Cillis <59309595+demic-dev@users.noreply.github.com> Date: Thu, 20 Feb 2025 04:07:46 +0100 Subject: [PATCH] fix: fixed infinite refetching on notifications and removed deprecated components in notification tabs (#270) --- src/app/(auth)/notifications/index.tsx | 84 +++++++++++++++----------- 1 file changed, 48 insertions(+), 36 deletions(-) diff --git a/src/app/(auth)/notifications/index.tsx b/src/app/(auth)/notifications/index.tsx index e74cd066..e93865f9 100644 --- a/src/app/(auth)/notifications/index.tsx +++ b/src/app/(auth)/notifications/index.tsx @@ -23,19 +23,17 @@ export default function NotificationsScreen() { const { data, fetchNextPage, - fetchPreviousPage, hasNextPage, - hasPreviousPage, isFetchingNextPage, isFetching, - isError, + isRefetching, error, refetch, } = useInfiniteQuery({ queryKey: ['notifications', activeTab], queryFn: fetchNotifications, getNextPageParam: (lastPage) => lastPage.nextPage, - getPreviousPageParam: (lastPage) => lastPage.prevPage, + getPreviousPageParam: (firstPage) => firstPage.prevPage, }) useEffect(() => { @@ -47,7 +45,19 @@ export default function NotificationsScreen() { setActiveTab(value) } - if (isFetching && !isFetchingNextPage) { + const handleInfiniteScroll = (_: { distanceFromEnd: number }) => { + if (isFetchingNextPage) { + return + } + + if (hasNextPage) { + fetchNextPage() + } + } + + // Since refetching cause the refetch of all the pages sequentially (longer waits), !isRefetching avoid unmonting of the FlatList and + // allow the user to see the past notifications in the meantime + if (isFetching && !isFetchingNextPage && !isRefetching) { return ( @@ -64,7 +74,7 @@ export default function NotificationsScreen() { } return ( - + - }> + - - - All - - + + All + + - - - + + - - - + + - - - + + - - - + page.data)} ItemSeparatorComponent={() => } renderItem={({ item }) => } - onEndReached={() => { - if (hasNextPage) fetchNextPage() - }} - refreshing={isFetching} - onRefresh={() => queryClient.invalidateQueries({ queryKey: ['notifications'] })} + // In case of duplicates, discriminate the item with id_index avoid printing errors in console + keyExtractor={(item, index) => `${item.id}_${index.toString()}`} + onEndReached={handleInfiniteScroll} + refreshing={isRefetching} + onRefresh={() => queryClient.invalidateQueries({ + queryKey: ['notifications'] } + )} onEndReachedThreshold={0.5} contentContainerStyle={{ flexGrow: 1 }} ListFooterComponent={() => - isFetchingNextPage ? ( - - - - ) : ( - - ) + + { + isFetchingNextPage ? + + : null + } + { + !hasNextPage ? + No more notifications for now! + : null + } + } />