P粉7656846022023-08-16 09:53:17
When you call handleSearchChange
and then call setCountriesToShow
to update the state:
setCountriesToShow( countries.filter(country => country .name .common .toLowerCase() .includes(event.target.value.toLowerCase()) ) )
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:
const handleSearchChange = (event) => { const newCountriesToShow = countries.filter(country => country .name .common .toLowerCase() .includes(event.target.value.toLowerCase()) ) setCountriesToShow(newCountriesToShow) setSearch(event.target.value) if (event.target.value.trim().length === 0) { setNotificationMessage(null) setShowShearched(false) } else if (newCountriesToShow.length <= 10) { setNotificationMessage(null) setShowShearched(true) } else { setNotificationMessage('list too long') setShowShearched(false) } }