I have a page with multiple forms on it. Anytime the form is submitted, I increase the value of actionsInARow
(that is stored in context). What I want to do is, as soon as this value is >0, start a 2 second timer where we will re-fetch data from the database. But, anytime the user submits another form, I want to reset the timer. Below is the implementation I have so far, implemented on the component at the page level. Is there a better way to do this?
const [timerId, setTimerId] = React.useState(0);
useEffect(() => {
if(actionsInARow === 0) {
return;
}
if(timerId !== 0) {
window.clearTimeout(timerId)
}
let timeoutId
timeoutId = window.setTimeout(() => {
setTimerId(0)
// dispach event in context to reset the count to 0
dispatch({ type: "RESET_COUNT" });
// re-run fetch request here...
}, 2000)
setTimerId(timeoutId);
return () => {
if(timeoutId !== 0) {
window.clearTimeout(timeoutId)
}
}
}, [actionsInARow]);
CodePudding user response:
Well for one thing you don't need the duplicate code to clear the timeout, the cleanup function will handle that for you so remove those 3 lines in the body. You also don't need the state of timerId
, unless you're using that somewhere else.
Those changes would look like this
useEffect(() => {
if(actionsInARow === 0) {
return;
}
let timeoutId = window.setTimeout(() => {
// dispach event in context to reset the count to 0
dispatch({ type: "RESET_COUNT" });
// re-run fetch request here...
}, 2000)
return () => {
window.clearTimeout(timeoutId)
}
}, [actionsInARow]);