Created
January 29, 2025 05:33
-
-
Save SolankiYogesh/a864b1937aa2cbd1735a99f8b8fa06e9 to your computer and use it in GitHub Desktop.
React Native Infinite List (Paginated List)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useRef, useCallback, useMemo } from 'react'; | |
import { FlatList, ActivityIndicator } from 'react-native'; | |
export default () => { | |
const pageCount = useRef(1); | |
const [list, setList] = useState([]); | |
const isLoadMore = useRef(true); | |
const [loadMore, setLoadMore] = useState(false); | |
const [isLoading, setIsLoading] = useState(false); | |
const getList = useCallback( | |
async (isPagination = false) => { | |
const isConnected = await getNetworkStatus(); | |
if (!isConnected) { | |
// Show toast for internet not connected | |
return; | |
} | |
let currentPage = 1; | |
if (loadMore || !isLoadMore.current) { | |
return; | |
} | |
if (isPagination) { | |
currentPage = pageCount.current + 1; | |
} | |
setIsLoading(!isPagination); | |
const payload = { | |
page: currentPage, | |
pageSize: 20, | |
}; | |
APICall('post', payload, 'getList') | |
.then((resp) => { | |
if (resp?.statusCode === 200 && resp?.data?.list) { | |
const { list } = resp.data; | |
if (list?.length > 0) { | |
setList((state) => { | |
return currentPage === 1 ? list : [...state, ...list]; | |
}); | |
setLoadMore(false); | |
isLoadMore.current = true; | |
pageCount.current = currentPage; | |
} else { | |
setList((state) => { | |
return currentPage === 1 ? [] : state; | |
}); | |
setLoadMore(false); | |
isLoadMore.current = false; | |
pageCount.current = currentPage; | |
} | |
} | |
setIsLoading(false); | |
}) | |
.catch(() => { | |
setIsLoading(false); | |
}); | |
}, | |
[loadMore] | |
); | |
const renderBottomView = useMemo(() => { | |
if (!loadMore) return null; | |
return <ActivityIndicator />; | |
}, [loadMore]); | |
return ( | |
<FlatList | |
renderItem={({ item, index }) => ( | |
// Render your item here | |
<></> | |
)} | |
showsVerticalScrollIndicator={false} | |
data={list} | |
ListFooterComponent={renderBottomView} | |
onEndReachedThreshold={0.5} | |
onEndReached={() => getList(true)} | |
/> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment