skip to Main Content

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?

2

Answers


  1. 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/[email protected]/umd/react.development.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    
    <div id="app"></div>
    Login or Signup to reply.
  2. You can use "useEffect" with "useState". Create one useState variable for storing the lastupdation time stamp so that you can compare it with the latest time and check whether the difference is more than 5 second or not

      const [pageNum,setPageNum] = useState(1)
      const [lastChangedTime, setLastChangedTime] = useState(Date.now());
    
      useEffect(() => {
        // Update lastChangedTime when pageNum changes
        setLastChangedTime(Date.now());
      }, [pageNum]);
     
    var isPageChanged = Date.now() - lastChangedTime >5000
    

    Then you can use isPageChanged variable for any condition

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search