I have a list of hospitals name which is coming from api. I have made a search functionality, where text typed by user will be matched with hospital name and resulted data will be shown on screen.
Below is my code:
const FindNameScreen = (props: any) => {
const [search, setSearch] = useState('');
const [filteredDataSource, setFilteredDataSource] = useState([]);
const [masterDataSource, setMasterDataSource] = useState([]);
const gethospitalList = useCallback(() => {
Apicall
.then(async (resp) => {
// console.log('resp>>>>>>>>>>>>>>>>>>>>>', resp.data);
if (resp) { setMasterDataSource(resp.data); }
else { Alert.alert('Error', resp); }
})
.catch((err: any) => {
console.log(err);
});
}, []);
useEffect(() => { gethospitalList();}, [gethospitalList]);
const searchFilterFunction = (text: any) => {
if (text) {
const newData = masterDataSource.filter(function (item: any) {
const itemData = item.hospital_name.toLowerCase();
const textData = text.toLowerCase();
return itemData.indexOf(textData) > -1;
});
setFilteredDataSource(newData);
setSearch(text);
} else {
setFilteredDataSource(masterDataSource);
setSearch(text);
}
};
const ItemView = ({item}) => {
return (
<View>
<Text style={styles.itemStyle}>{item.hospital_name}</Text>
</View>
);
};
return (
<>
<TextInput
style={styles.textInputStyle}
onChangeText={(text) => searchFilterFunction(text)}
value={search}
underlineColorAndroid="transparent"
placeholder="Search Here"
selectionColor="#4FE6AF"
/>
<View>
<FlatList
data={filteredDataSource}
keyExtractor={(item, index) => index.toString()}
renderItem={ItemView}
/>
</View>
</>
);
};
export default FindNameScreen;
Initially I have to show all the hospital names, and then when user types something then according to that the list are getting updated. All of these are working fine.
My problem is when the TextInput is empty, all the hospital name should be shown, but sometimes I am getting only two name, sometimes I am getting all the name. This should not happen. When TextInput is empty then all the names should be shown in list.
Initially, your Flatlist won't render any elements because the filteredDataSource state is blank at the beginning.
searchFilterFunction will only be triggered once you type something in TextInput. So, to display all the names at the beginning, try this:
<FlatList
data={
search === '' && filteredDataSource.length === 0
? masterDataSource
: filteredDataSource
}
keyExtractor={(item, index) => index.toString()}
renderItem={ItemView}
/>