import React, { useState, useEffect } from 'react';
import {
View,
Text,
FlatList,
ActivityIndicator,
StyleSheet,
RefreshControl
} from 'react-native';
import { fetchContacts, syncContacts } from '@contactsmanager/rn';
const ContactListScreen = () => {
const [contacts, setContacts] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
useEffect(() => {
loadContacts();
}, []);
const loadContacts = async () => {
setIsLoading(true);
try {
const fetchedContacts = await fetchContacts();
setContacts(fetchedContacts);
} catch (error) {
console.error('Error loading contacts:', error);
} finally {
setIsLoading(false);
}
};
const handleRefresh = async () => {
setIsRefreshing(true);
try {
await syncContacts();
// Reload contacts after sync
await loadContacts();
} catch (error) {
console.error('Error syncing contacts:', error);
} finally {
setIsRefreshing(false);
}
};
const renderContactRow = ({ item }) => (
<View style={styles.contactRow}>
<Text style={styles.contactName}>{item.displayName || 'Unknown'}</Text>
{item.phoneNumbers && item.phoneNumbers.length > 0 && (
<Text style={styles.contactDetail}>{item.phoneNumbers[0].value}</Text>
)}
</View>
);
return (
<View style={styles.container}>
{isLoading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" />
<Text style={styles.loadingText}>Loading contacts...</Text>
</View>
) : (
<FlatList
data={contacts}
renderItem={renderContactRow}
keyExtractor={(item) => item.id}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={handleRefresh}
/>
}
ListEmptyComponent={
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No contacts found</Text>
</View>
}
/>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
loadingText: {
marginTop: 10,
fontSize: 16,
color: '#666',
},
contactRow: {
padding: 15,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
contactName: {
fontSize: 16,
fontWeight: '600',
},
contactDetail: {
fontSize: 14,
color: '#666',
marginTop: 4,
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 50,
},
emptyText: {
fontSize: 16,
color: '#666',
},
});
export default ContactListScreen;