get the latest value after timeout

Solutions on MaxInterview for get the latest value after timeout by the best coders in the world

showing results for - "get the latest value after timeout"
Angel
05 Mar 2016
1import React, {useState, useEffect, useRef} from 'react';
2
3function InputField() {
4
5  const [value, setValue] = useState('');       // STATE FOR THE INPUT VALUE
6  const timeoutRef = useRef(null);              // REF TO KEEP TRACK OF THE TIMEOUT
7
8  function validate() {                         // VALIDATE FUNCTION
9    console.log('Validating after 500ms...');
10  }
11
12  useEffect(() => {                             // EFFECT TO RUN AFTER CHANGE IN VALUE
13    if (timeoutRef.current !== null) {          // IF THERE'S A RUNNING TIMEOUT
14      clearTimeout(timeoutRef.current);         // THEN, CANCEL IT
15    }
16
17    timeoutRef.current = setTimeout(()=> {      // SET A TIMEOUT
18      timeoutRef.current = null;                // RESET REF TO NULL WHEN IT RUNS
19      value !== '' ? validate() : null;         // VALIDATE ANY NON-EMPTY VALUE
20    },500);                                     // AFTER 500ms
21  },[value]);                                   // RUN EFFECT AFTER CHANGE IN VALUE
22
23  return(                                       // SIMPLE TEXT INPUT
24    <input type='text' 
25      value={value} 
26      onChange={(e) => setValue(e.target.value)}
27    />
28  );
29
30}