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.
When you call
handleSearchChangeand then callsetCountriesToShowto udpate that state:You are triggering a re-render. The newly updated state value will only become available then, in the upcoming re-render, that's why it's lagging behind.
If you want to use that value below, you need to store it in a variable first: