2021-07-31 02:45:18 +02:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
import {
|
|
|
|
disconnectGasFeeEstimatePoller,
|
|
|
|
getGasFeeEstimatesAndStartPolling,
|
2021-08-04 23:53:13 +02:00
|
|
|
addPollingTokenToAppState,
|
|
|
|
removePollingTokenFromAppState,
|
2021-07-31 02:45:18 +02:00
|
|
|
} from '../store/actions';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Provides a reusable hook that can be used for safely updating the polling
|
|
|
|
* data in the gas fee controller. It makes a request to get estimates and
|
|
|
|
* begin polling, keeping track of the poll token for the lifetime of the hook.
|
|
|
|
* It then disconnects polling upon unmount. If the hook is unmounted while waiting
|
|
|
|
* for `getGasFeeEstimatesAndStartPolling` to resolve, the `active` flag ensures
|
|
|
|
* that a call to disconnect happens after promise resolution.
|
|
|
|
*/
|
|
|
|
export function useSafeGasEstimatePolling() {
|
|
|
|
useEffect(() => {
|
|
|
|
let active = true;
|
|
|
|
let pollToken;
|
2021-08-04 23:53:13 +02:00
|
|
|
|
|
|
|
const cleanup = () => {
|
|
|
|
active = false;
|
|
|
|
if (pollToken) {
|
|
|
|
disconnectGasFeeEstimatePoller(pollToken);
|
|
|
|
removePollingTokenFromAppState(pollToken);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-07-31 02:45:18 +02:00
|
|
|
getGasFeeEstimatesAndStartPolling().then((newPollToken) => {
|
|
|
|
if (active) {
|
|
|
|
pollToken = newPollToken;
|
2021-08-04 23:53:13 +02:00
|
|
|
addPollingTokenToAppState(pollToken);
|
2021-07-31 02:45:18 +02:00
|
|
|
} else {
|
|
|
|
disconnectGasFeeEstimatePoller(newPollToken);
|
2021-08-04 23:53:13 +02:00
|
|
|
removePollingTokenFromAppState(pollToken);
|
2021-07-31 02:45:18 +02:00
|
|
|
}
|
|
|
|
});
|
2021-08-04 23:53:13 +02:00
|
|
|
|
|
|
|
window.addEventListener('beforeunload', cleanup);
|
|
|
|
|
2021-07-31 02:45:18 +02:00
|
|
|
return () => {
|
2021-08-04 23:53:13 +02:00
|
|
|
cleanup();
|
|
|
|
window.removeEventListener('beforeunload', cleanup);
|
2021-07-31 02:45:18 +02:00
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
}
|