import React, { useState } from 'react';
import { View, Text, FlatList, RefreshControl, StyleSheet } from 'react-native';
export default function PullToRefreshScreen() {
const [refreshing, setRefreshing] = useState(false);
const [items, setItems] = useState([
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5'
]);
const onRefresh = () => {
setRefreshing(true);
setTimeout(() => {
const newTimestamp = new Date().toLocaleTimeString();
setItems([
`Refreshed at ${newTimestamp} - Item 1`,
`Refreshed at ${newTimestamp} - Item 2`,
`Refreshed at ${newTimestamp} - Item 3`,
`Refreshed at ${newTimestamp} - Item 4`,
`Refreshed at ${newTimestamp} - Item 5`
]);
setRefreshing(false);
}, 2000);
};
return (
<View style={styles.container}>
<FlatList
data={items}
keyExtractor={(item) => item}
renderItem={({ item }) => <Text style={styles.item}>{item}</Text>}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, paddingTop: 50 },
item: { padding: 20, borderBottomWidth: 1, borderColor: '#ccc' }
});This solution uses React Native's RefreshControl inside a FlatList to enable pull-to-refresh functionality.
When the user pulls down, onRefresh is called. It sets refreshing state to true, which shows the spinner.
We simulate fetching new data with setTimeout for 2 seconds. After that, we update the list items with new strings that include the current time to show the refresh happened.
Finally, refreshing is set to false to hide the spinner.
This pattern is common in mobile apps to let users refresh content easily.