I have a small issue related to some basic search box logic which returns results from Firebase.
The issue is related to my useState query. When the page is loaded the state is set to the correct initial state which is an empty string. When typing in the search box the onChange handler gets updated as expected and runs the function for the search.
However, when all characters are removed from the search box, the state of query still holds onto the last character. For example
if you search ‘Car’ in the search box and then remove all characters, the search state will hold onto ‘C’ therefore running the function whilst the front end shows an empty search box
Code below
const [searchResults, setSearchResults] = useState([])
const [searchQuery, setSearchQuery] = useState('')
const handleSearch = async (query) => {
const results = [];
if (query) {
setSearchQuery(query);
try {
const prod = await firestore.collection('products').get();
prod.docs.forEach((doc) => {
const searchableIndex = doc.data().searchableIndex;
if (searchableIndex) {
// Convert the search query to lowercase for case-insensitive matching
const lowerCaseQuery = query.toLowerCase();
// Check if any key in the searchableIndex contains the search query as a substring
if (Object.keys(searchableIndex).some(key => key.includes(lowerCaseQuery))) {
results.push({
title: doc.data().title
});
}
}
});
setSearchResults(results);
} catch (error) {
console.error('Error fetching products:', error);
}
} else {
setSearchResults([]);
setSearchQuery('')
console.log(setSearchResults.length)
}
};
useEffect(() => {
}, [searchResults, searchQuery, handleSearch]);
return (
<>
<Animatable.View animation={'slideInUp'} duration={800} style={styles.searchContainer}>
<View style={styles.searchIconContainer}>
<AntDesign style={{paddingLeft: 10, color: "#37BD6B"}} name="search1" size={19} />
</View>
<TextInput onChangeText={(e) => handleSearch(e)} autoFocus={true} style={styles.searchBar}/>
</Animatable.View>
<View>
{searchResults.map((seller, index) => (
<View key={index} style={{backgroundColor: 'grey', padding: 15, }}>
<Text>{seller.title}</Text>
<Text>{seller.accountNumber}</Text>
</View>
))}
</View>
</>
)
1