I am learning React Native and I have a problem with the search bar, here I put my code.
export default SearchBar = ({ setPokemonDetails, pokemonsList }) => {
const handlePokemonSearch = (text) => {
const filteredItems = pokemonsList.filter(item => {
return item.name.toLowerCase().includes(text.toLowerCase())
})
setPokemonDetails(filteredItems)
}
return (
<View style={styles.container}>
<TextInput style={styles.textInput} placeholder="Search Pokemon"
onChangeText={(text) => {
handlePokemonSearch(text)
}} />
</View>
);
}
Here is The Home Component, where I call de SearchBar Component:ç
export default function Home() {
const { pokemonDetails, setPokemonDetails, setIsLoading, isLoading, isError } = useFetchPokemons()
return (
<View style={{ padding: 10 }}>
<SearchBar setPokemonDetails={setPokemonDetails} pokemonsList={pokemonDetails} />
<FlatList
data={pokemonDetails}
keyExtractor={(item) => item.name}
renderItem={({ item }) => <Card pokemon={item} />}
/>
</View>
);
}
This code works halfway because it filters really well while you are writting BUT, when you delete some letters, it does not filter again. For example:
I have an array with this pokemons:
- Charmander
- Charmeleon
- Charizard
If I write ‘charm’, the search bar finds correctly there are only 2 (Charmander and Charmeleon), BUT if delete the ‘m’ letter, it does not show the 3 pokemons again and keep showing Charmander and Charmeleon.
Does anyone knows how can I solve this problem?
2
Answers
I think to be able to better diagnose the issue, we would need to look at how you are calling your
SearchBar
component on your main screen. Could it be thatsetPokemonDetails
sets the state ofpokemonsList
, causing this issue? For example, you might not be using two separate state variables to store the PokemonList as well as PokemonDetails.I would make use of console.log() within
handlePokemonSearch
and see howpokemonsList
as well as thefilteredItems
vary with text input.Hope this helps in any small way!
When you
setPokemonDetails(filteredItems)
, you are permanently trimming down the list that<SearchBar />
receives in itspokemonsList
prop. You don’t want to alter the list when you are searching items, you simply want a filtered view of it to be rendered. So instead of setting the list itself, you need to track a new piece of state for the search text and set that instead.As an example: