Issue
I'm being struggling a couple of days with search bar in my app, the problem is that when I search with particular name of products the products with that name show up but when I clear the search bar the entire products disappear not showing up after clearing search bar?
Here is my Code:
const Home =()=>{
// State
const [categories, setCategories] = useState(categoryData)
const [selected, setSelected] = useState(null)
const [productst, setProducts] = useState (ProductData)
// seach function
function handleSearch(text){
const filterData = productst.filter((item)=>{
return item.name.toLowerCase().includes(text.toLowerCase())
})
setProducts(filterData)
}
function renederHeader(){
return(
//Search Input
<View style={{ marginTop:SIZES.margin,}} >
<TouchableOpacity
onPress={()=>{}}
style={{
flexDirection:'row',
alignSelf:'center',
}}>
<TextInput
placeholder=" Find Your Favourite..."
placeholderTextColor={COLORS.lightGrey20}
// value={}
onChangeText={text=>handleSearch(text)}
/>
</TouchableOpacity>
</View>
}
function renderCategories(){
return(
<View
style={{
marginTop:20,
}}
>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={categories}
keyExtractor={item=>item.id}
renderItem={({item,index})=>{
return(
<TouchableOpacity
onPress={()=>onSelecteCategory(item)}>
)
My Product Data:
export const ProductData = [
{
id: 1,
name:'Coffee',
categories: [1],
image: require('../asset/images/coffee1.png'),
index: 0,
},
{
id: 2,
name:'Coffee',
categories: [1],
image: require('../asset/images/coffee2.png'),
index: 0,
},
{
id: 3,
name:'Coffee',
categories: [1],
image: require('../asset/images/coffee3.png'),
index: 0,
},
{
id: 4,
name:'Tea',
categories: [2],
image: require('../asset/images/Tea1.png'),
index: 0,
}, {
id: 5,
name:'Tea',
categories: [2],
image: require('../asset/images/Tea2.png'),
index: 0,
},
{
id: 6,
name:'Tea',
categories: [2],
image: require('../asset/images/Tea3.png'),
index: 0,
},
{
id: 7,
name:'choclate',
categories: [3],
image: require('../asset/images/choclate1.png'),
index: 0,
},
{
id: 8,
name:'choclate',
categories: [3],
image: require('../asset/images/choclate2.png'),
index: 0,
},
{
id: 9,
name:'choclate',
categories: [3],
image: require('../asset/images/choclate3.png'),
index: 0,
},
]
So, Please if anyone can help me how to search in bar and get the certain products and when I clear the search bar the all products should show up normally not disappear as it is now.
Solution
Your handler function takes the state variable products as input for the filter. Therefore the array of possible values decreases with every iteration of filtering, even when the input is deleted.
Try to instead use the product data array as input. This will cause the filter to always look at the whole dataset, whenever the input changes.
Answered By - Egge
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.