I am trying to create an autocomplete drop-down search bar, which I found Here and I try to use it with populated data dataSource
with worked well, but when I used it with my fetched data from an API it don’t work see code below
App.js
const App = () => {
const [dataSource] = useState(['apple', 'banana', 'cow', 'dex', 'zee', 'orange', 'air', 'bottle'])
const [filtered, setFiltered] = useState(dataSource);
const [searching, setSearching] = useState(false);
const onSearch = (text) => {
if (text) {
setSearching(true)
const temp = text.toLowerCase()
const tempList = dataSource.filter(item => {if (item.match(temp))return item})
setFiltered(tempList)
} else {
setSearching(false)
}
}
return (
<SafeAreaView style={styles.container}>
<TextInput
style={styles.textInput}
placeholder="Search"
placeholderTextColor='white'
onChangeText={onSearch}
/>
{ searching &&
<SearchDropDown
dataSource={filtered}
/>
}
</SafeAreaView>
)
}
SearchDropDown.js
const SearchDropDown = (props) => {
const {dataSource} = props;
return (
<View>
{
dataSource.map((item,index) => {
return (
<View>
<View key={index}>
<Text style={{color: 'black'}}>{item}</Text>
</View>
</View>
)
})
}
</View>
)
}
This is my code I replaced dataSource
with artistData
which is fetching my data from my API
const [artistData, setArtist] = useState([]);
const [filtered, setFiltered] = useState(artistData);
const [searching, setSearching] = useState(false);
useEffect(() => {
axios.get(serveURL)
.then((response) => setArtist(response.data))
.catch(error => { console.log(error) });
}, []);
const onSearch = (text) => {
if (text) {
setSearching(true)
const temp = text.toLowerCase()
const tempList = artistData.filter(item => {if (item.match(temp))return item})
setFiltered(tempList)
} else {
setSearching(false)
}
}
return (
<SafeAreaView style={styles.container}>
<TextInput
style={styles.textInput}
placeholder="Search"
placeholderTextColor='white'
onChangeText={onSearch}
/>
{ searching &&
<SearchDropDown
artistData={filtered}
/>
}
</SafeAreaView>
)
Also make the changes in SearchDropDown.js
from const {dataSource} = props;
and dataSource.map
to this const {artistData} = props;
and artistData.map
but still did not work, I check the if there is data in artistData
with flatlist
see below
<FlatList
data = {serveURL}
listKey="artist-data"
keyExtractor={item => item.id}
renderItem={({item}) => {
return (
<Text>{item.artist_name}</Text>
)
}}
/>
It shows that there is data there, please I will need your help with this, Thank You.