Skip to content

Instantly share code, notes, and snippets.

@jonasgroendahl
Created October 22, 2020 21:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasgroendahl/527a41a38ab67869ed798461940f147d to your computer and use it in GitHub Desktop.
Save jonasgroendahl/527a41a38ab67869ed798461940f147d to your computer and use it in GitHub Desktop.
import React, {useState} from 'react';
import {
Button,
Dimensions,
FlatList,
SafeAreaView,
StyleSheet,
Text,
View,
} from 'react-native';
import {useInfiniteQuery} from 'react-query';
const App: React.FC = () => {
const [start, setStart] = useState(0);
const {data, isLoading, fetchMore} = useInfiniteQuery(
'posts',
async (_, nextId = 0) => {
console.log('start', start, nextId);
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_start=${nextId}&_limit=10`,
);
//if(response.headers['content-type'] === 'application/json')
const posts = await response.json();
console.log('data', data);
return posts;
},
);
if (isLoading) {
return <Text>Loading...</Text>;
}
const getMore = () => {
// usually check for next cursor
// alternative way
if (data[data?.length - 1].length === 0) {
return;
}
const newStartValue = start + 10;
fetchMore(newStartValue); // i can pass a new value into cb of useInfiniteQuery, state hook will not be updated in time
setStart(newStartValue);
};
console.log('data real', data);
return (
<SafeAreaView>
<Text>Hello lets scroll</Text>
<FlatList
data={data?.flat()}
keyExtractor={(item) => item.id}
renderItem={({item}) => (
<View style={styles.view}>
<Text>{item.id}</Text>
</View>
)}
onEndReached={getMore}
/>
<Button title="Fetch More" onPress={getMore} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
view: {
height: 300,
width: Dimensions.get('screen').width - 10,
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 20,
backgroundColor: '#eee',
margin: 5,
},
});
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment