I am trying to detect if the page number (which is created by useState hook) has changed in last 5 seconds to make a conditional if statement. Is this possible in React/JavaScript?
>Solution :
One option might be to update the state you have that probably looks something like this:
const [page, setPage] = useState(0)
To something like this:
const [pageState, setPageState] = useState({ page: 0, lastUpdated: 0 })
This way, every time you update page, you also update lastUpdated, so you can do something like:
const updatedWithinTheLastFiveSeconds = Date.now() - pageState.lastUpdated <= 5000
You can also store the lastUpdated value in a new state piece if you can’t or don’t want to change the one you already have.
Also, you can potentially use setInterval to continuously update updatedWithinTheLastFiveSeconds (if you want to implement something like a progress bar) or just use setTimeout if you just need to know when the 5 seconds have passed, like in the example below:
const App = () => {
const timeoutRef = React.useRef(0)
React.useEffect(() => () => {
// Clear the tiemout when the component unmounts:
clearTimeout(timeoutRef.current)
}, [])
const [page, setPage] = React.useState(0);
const [updatedWithinTheLastFiveSeconds, setUpdatedWithinTheLastFiveSeconds] = React.useState(false);
const handleClick = React.useCallback(() => {
setPage(prevPage => prevPage + 1)
setUpdatedWithinTheLastFiveSeconds(true)
setTimeout(() => {
setUpdatedWithinTheLastFiveSeconds(false)
}, 5000)
});
return (
<button onClick={ handleClick } disabled={ updatedWithinTheLastFiveSeconds }>
{ updatedWithinTheLastFiveSeconds ? 'Wait...' : `Go to page ${ page + 1 }` }
</button>
);
}
ReactDOM.render(<App />, document.querySelector('#app'));
body,
button {
font-family: monospace;
}
body, p {
margin: 0;
}
#app {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
}
button {
margin: 32px 0;
padding: 8px;
border: 2px solid black;
background: transparent;
cursor: pointer;
border-radius: 2px;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>