Answers for "get the latest value after timeout"

0

get the latest value after timeout

import React, {useState, useEffect, useRef} from 'react';

function InputField() {

  const [value, setValue] = useState('');       // STATE FOR THE INPUT VALUE
  const timeoutRef = useRef(null);              // REF TO KEEP TRACK OF THE TIMEOUT

  function validate() {                         // VALIDATE FUNCTION
    console.log('Validating after 500ms...');
  }

  useEffect(() => {                             // EFFECT TO RUN AFTER CHANGE IN VALUE
    if (timeoutRef.current !== null) {          // IF THERE'S A RUNNING TIMEOUT
      clearTimeout(timeoutRef.current);         // THEN, CANCEL IT
    }

    timeoutRef.current = setTimeout(()=> {      // SET A TIMEOUT
      timeoutRef.current = null;                // RESET REF TO NULL WHEN IT RUNS
      value !== '' ? validate() : null;         // VALIDATE ANY NON-EMPTY VALUE
    },500);                                     // AFTER 500ms
  },[value]);                                   // RUN EFFECT AFTER CHANGE IN VALUE

  return(                                       // SIMPLE TEXT INPUT
    <input type='text' 
      value={value} 
      onChange={(e) => setValue(e.target.value)}
    />
  );

}
Posted by: Guest on August-26-2021

Code answers related to "get the latest value after timeout"

Code answers related to "Javascript"

Browse Popular Code Answers by Language