I'm trying to make an input filtered based list that only shows results when there are 10 or less objects, but the array.length is always lagging one step behind the input.
const [countriesToShow, setCountriesToShow] = useState([])
const [newSearch, setSearch] = useState('')
const [showSearched, setShowShearched] = useState(true)
const [notificationMessage, setNotificationMessage] = useState(null)
useEffect(() => {
console.log(countriesToShow.length)
},[countriesToShow])
const handleSearchChange = (event) => {
setCountriesToShow(countries.filter(country =>
country.name.common.toLowerCase().includes(event.target.value.toLowerCase())))
setSearch(event.target.value)
if (event.target.value.trim().length === 0) {
setNotificationMessage(null)
setShowShearched(false)
}
else if (countriesToShow.length <= 10) {
setNotificationMessage(null)
setShowShearched(true)
console.log(countriesToShow.length)
}
else {
setNotificationMessage('list too long')
setShowShearched(false)
console.log(countriesToShow.length)
}
}
I managed to get the console print the right length with the help of Effect Hook but I'm stumped about how to implement the same to the 'else if (countriesToShow.length <= 10)' as it still lags behind the input.