Gif file here
In the above gif, you can see that when I scroll to the end, after loading extra data and appending it, the scroll gets reset and scrolled to the top.
Here's the code
State variable declaration
const [data, setData] = useState([]); //Contains the fetched data
const [isFetching, setFetching] = useState(false); //To indicate status
Fetch data function
const fetchMarketData = async () => {
const marketData = await getCryptoMarketData({ page });
if (marketData.status != 401) {
setData(
data.length > 0
? marketData.filter((d) => data.forEach((s) => d.ticker != s.ticker)) //Appending new data id the data is not empty
: marketData //If the data is empty then it's the first fetch.
);
setFetching(false);
} else {
setFetching(false);
Alert.alert(marketData, "Sorry for the inconvenience");
}
};
Use Effect function
useEffect(() => {
setFetching(true);
const data = async () => {
await fetchMarketData();
};
data();
}, []);
Load more data
const handleLoadMore = () => {
setFetching(true);
setPage(() => page + 1);
() => fetchMarketData;
};
Footer indicator
const renderFooter = () => {
return isFetching ? (
<View style={{ marginTop: 10, alignItems: "center" }}>
<ActivityIndicator size="large" color="#1f1f1f" />
</View>
) : null;
};
The Flatlist
<BottomSheetFlatList
ref={scrollRef}
data={data}
style={{ backgroundColor: "white" }}
keyExtractor={(item) => item.id}
renderItem={renderItems} //Render items just displays the data
maxToRenderPerBatch={20}
scrollEventThrottle={16}
onEndReached={handleLoadMore}
onEndReachedThreshold={0}
ListFooterComponent={renderFooter}
/>
Reason why is because u REPLACING and not APPENDING state, in other words you replacing data not adding new
Replacing:
setState([{}])
Appending:
let nextPageData = [{}]
setState([...state, ...nextPageData])
so fix for your case is this ( but i m not sure when FALSE in if happends, cuz normal API doesnt send u old data just always new ... this is maybe bug on your side too )
let newData = data.length > 0 ? marketData.filter((d) => data.forEach((s) => d.ticker != s.ticker)) : marketData
setData([...data, ...newData]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With