I am new to react-native and javascript. I am trying to filter an array of objects, where each object represents a country and has a member variable called name. I have created the following search filter to save countries with search keyword.
I have console.logged every step in between the following function, from array of country's state to filter's state and even the condition includes() also returns true.
const App = () => {
const [countries,setCountries] = useState([])
const [filter,setFilter] = useState('')
useEffect(() =>{
axios.get('https://restcountries.eu/rest/v2/all')
.then(response => setCountries(response.data))
}, [])
//console.log('countries[] = ',countries)
const rows = () => {
const len = countriesToShow.length
if(len > 10){
return(<p>Too many matches, specify another filter</p>)
}
else if(len >=1 && len <= 10){
return(countriesToShow.map(country => <p>{country.name}</p>))
}
}
const handleFilterChange = (event) => {
setFilter(event.target.value)
}
const countriesToShow = filter === '' ? [] : countries.filter(country => country.name.toLowerCase().includes(filter.toLowerCase()))
return(
<div>
find countries
<input value={filter} onChange={handleFilterChange} />
{rows()}
</div>
)
}
export default App;
I expect an array with the filtered country names but I am actually getting an empty array.
const countries = [{name: 'USA'}, {name: 'Canada'}]; let filter = 'Canada';before your code, countriesToShow contains[{name:'Canada'}]once it runs.