search

Home  >  Q&A  >  body text

Why is the array.length method always one step slower than the input step in the handleChange event handler?

<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粉596161915P粉596161915471 days ago389

reply all(1)I'll reply

  • P粉765684602

    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)
      }
    }

    reply
    0
  • Cancelreply