I have 2 useEffects inside my component both with setTimeout and clearTimeout methods inside of them. They both update based on the same props and the conditions inside them are the same however one is set to fire every 3 seconds and the other should fire every 1 minute.
My issue is the one that should update every minute is not firing at all.
I think it may be reseting every time the props update (every 3 seconds when i console inside the if
statement it is consoling) but im not sure how to work around this since the props will update every time the first one is fired.
My goal here is
these are my useEffects:
useEffect(() => {
if(!providerData?.providerAvailable ) {
sendMessage({
code: 'NO_PROVIDER_AVAILABLE',
value: 'No provider currently available',
});
const timerId = window.setTimeout(() => providerRefetch(), 3000);
return () => window.clearTimeout(timerId);
} else {
return;
}
}, [providerData]);
// send No provider event every minute
useEffect(() => {
if ( !providerData?.providerAvailable ) {
const eventId = window.setTimeout(() => sendEvent(), 60000, {
key: 'NO_PROVIDER_AVAILABLE',
description: 'No provider currently available',
});
return () => window.clearTimeout(eventId);
} else {
return;
}
}, [providerData]);
Instead of basing my second useEffect off of the same props as the first I created a count that increments up every time the first is called and the 2nd useEffect updates when the count updates:
const [callCount, setCallCount] = useState(0);
useEffect(() => {
if (
providerError ||
(!providerData?.providerAvailable && providerData?.providerState !== 'engaged')
) {
if (callCount < 21) {
let count = callCount + 1;
setCallCount(count);
} else {
setCallCount(0);
}
sendMessage({
type: 'EVENT',
code: 'NO_PROVIDER_AVAILABLE',
value: 'No provider currently available',
});
const timerId = window.setTimeout(() => providerRefetch(), 3000);
return () => window.clearTimeout(timerId);
} else {
return;
}
}, [providerData, providerRefetch, providerError]);
// send No provider event every minute
useEffect(() => {
if (callCount === 2) {
sendEvent({
key: 'NO_PROVIDER_AVAILABLE',
description: 'No provider currently available',
})
} else {
return;
}
}, [callCount]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.