From 39833cabf26df93395bc30c9a690eced466d4f2b Mon Sep 17 00:00:00 2001 From: Imbus Date: Fri, 15 Dec 2023 03:50:23 +0100 Subject: [PATCH] Unique key fix --- src/components/PostsContainer.tsx | 45 +++++++++++++------------------ 1 file changed, 19 insertions(+), 26 deletions(-) diff --git a/src/components/PostsContainer.tsx b/src/components/PostsContainer.tsx index be439d6..46011ab 100644 --- a/src/components/PostsContainer.tsx +++ b/src/components/PostsContainer.tsx @@ -6,48 +6,45 @@ import { style } from "../util/style"; import { SafeAreaView } from "react-native"; import { VirtualizedList } from "react-native"; +const WINDOW_SIZE = 20; + export function PostsContainer({ navigation }): JSX.Element { const [postData, setPostData] = React.useState([]); - const [page, setPage] = React.useState(0); + const [offset, setOffset] = React.useState(0); const [refreshing, setRefreshing] = React.useState(false); const handleEndReached = (): void => { - setPage((prevPage) => prevPage + 1); + setOffset(offset + WINDOW_SIZE); + fetchMorePosts(); }; + function onRefresh(): void { + refreshPosts(); + } + React.useEffect(() => { refreshPosts(); }, []); - React.useEffect(() => { - fetchMorePosts(); - }, [page]); - // Full refresh function refreshPosts(): void { - async function fetchPosts(): Promise { - setPage(0); - setPostData(await getPostsInterval(0, 10)); - } + setRefreshing(true); setPostData([]); + setOffset(WINDOW_SIZE); + async function fetchPosts(): Promise { + setPostData(await getPostsInterval(0, WINDOW_SIZE)); + } fetchPosts(); + setRefreshing(false); } - // Incremental fetch, should prune old posts function fetchMorePosts(): void { async function fetchPosts(): Promise { - const newPosts = await getPostsInterval(page * 10, 10); - setPostData((oldPosts) => [...oldPosts, ...newPosts]); + setPostData([...postData, ...(await getPostsInterval(offset, WINDOW_SIZE))]); } fetchPosts(); } - function onRefresh(): void { - setRefreshing(true); - refreshPosts(); - setRefreshing(false); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars const getItemCount = (_data: unknown): number => postData.length; @@ -60,10 +57,8 @@ export function PostsContainer({ navigation }): JSX.Element { ( - - )} - keyExtractor={(item: Post) => item.id + item.createdAt} + renderItem={({ item }) => } + keyExtractor={(item: Post) => item.id} getItemCount={getItemCount} getItem={getItem} onEndReached={handleEndReached} @@ -88,7 +83,5 @@ function NavButton({ onPress: () => void; text: string; }): JSX.Element { - return ( -