Why is the array.length method always one step slower than the input step in the handleChange event handler?
P粉596161915
P粉596161915 2023-08-15 18:06:33
0
1
401
<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>
P粉596161915
P粉596161915

reply all(1)
P粉765684602

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)
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template