In React Native's FlatList or SectionList, fetching paginated data when user scrolls to the end of the list is easy to implement with onEndReached
.
However, if the initialScrollIndex
is set, and user scrolls up, is there any way to fetch data?
liked the question :)
It can be done, ive just achieved it, do check it out on expo snack https://snack.expo.dev/ZY7MlIX8M
import React,{useState,useRef} from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar } from 'react-native';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item2',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item3',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item4',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item5',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item6',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item7',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item7',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item8',
},
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
const [firstScroll,setFirst] = useState(null)
const currrentY = useRef(null);
const renderItem = ({ item }) => (
<Item title={item.title} />
);
const onScroll = (event) =>{
if(firstScroll === null){
setFirst(event.nativeEvent.contentOffset.y)
}
currrentY.current = event.nativeEvent.contentOffset.y
}
//here you will get when the user scrolled after initial index whether the user moved up, and then call api
const onScrollENd = (event) => {
console.log("false",event.nativeEvent.contentOffset.y)
if(event.nativeEvent.contentOffset.y < firstScroll ){
console.log("went up , call api here")
}
}
return (
<SafeAreaView style={styles.container}>
<FlatList
onScrollEndDrag={onScrollENd}
onScroll={onScroll}
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
initialScrollIndex={6}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 40,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 40,
},
});
export default App;
Hope it helps , feel free for doubts