Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks useState not updating with onChange [duplicate]

UPDATED QUESTION:

If I type something in the input field before I scroll the expanded prop gets set to true - correct

If I scroll down - expanded gets set to false - correct

If I type something in the input field now expanded is still false - I expect expanded to be set to true again.

code:

export default () => {

const [expanded, setExpanded] = useState(true)

let searchInput = React.createRef()
let scrollTopValue = 0;

function handleSearchInput() {
    console.log(Boolean(searchInput.current.value.length))
    setExpanded(Boolean(searchInput.current.value.length)) // first time true, don't get re triggered

}

useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
}, []);

function handleScroll() {
    setExpanded(scrollTopValue > document.documentElement.scrollTop)
    scrollTopValue =  document.documentElement.scrollTop
}

return (
<header>
   {expanded? 'expanded': 'nope'}
    <input role="search" ref={searchInput} onChange={handleSearchInput}></input>

</header>)
}
like image 232
Björn Hjorth Avatar asked Mar 16 '19 07:03

Björn Hjorth


1 Answers

Updating state in react is not guaranteed synchronous call. So, when you are calling console.log(expanded) just after changing state it won't return the new state. Your component will receive new state on the re-render.

You can also refer to this blog https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3

Another reference:- useState set method not reflecting change immediately

like image 106
cEeNiKc Avatar answered Oct 04 '22 09:10

cEeNiKc