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>)
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With