Why is the array.length method always one step slower than the input step in the handleChange event handler?
P粉596161915
2023-08-15 18:06:33
<p>I'm trying to create a list that filters based on input and only displays results if there are 10 or less objects, but array.length always lags behind the input. </p>
<pre class="brush:php;toolbar:false;">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)
}
}</pre>
<p> I managed to print out the length correctly with the help of Effect Hook, but I'm confused on how to implement this into 'else if (countriesToShow.length <= 10)' as it still lags behind the input. </p>
When you call
handleSearchChange
and then callsetCountriesToShow
to update the state:You triggered a rerender. The newly updated state value will only become available on the upcoming re-render, which is why it lags behind.
If you want to use the value below, you need to store it in a variable first: