Skip to content

Commit

Permalink
Ensure analytics observer instance is not lost.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hyperkid123 committed Jun 13, 2023
1 parent fa57b80 commit 38b014c
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/analytics/SegmentProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,21 @@ const getAPIKey = (env: SegmentEnvs = 'dev', module: SegmentModules, moduleAPIKe
}[env]?.[module] ||
KEY_FALLBACK[env];

let observer: MutationObserver | undefined;
const registerAnalyticsObserver = () => {
// never override the observer
if (observer) {
return;
}
console.log('Calling register observer');
/**
* We ignore hash changes
* Hashes only have frontend effect
*/
let oldHref = document.location.href.replace(/#.*$/, '');

const bodyList = document.body;
const observer = new MutationObserver((mutations) => {
observer = new MutationObserver((mutations) => {
mutations.forEach(() => {
const newLocation = document.location.href.replace(/#.*$/, '');
if (oldHref !== newLocation) {
Expand All @@ -99,7 +105,6 @@ const registerAnalyticsObserver = () => {
childList: true,
subtree: true,
});
return observer.disconnect;
};

const isInternal = (email = '') => /@(redhat\.com|.*ibm\.com)$/gi.test(email);
Expand Down Expand Up @@ -255,8 +260,11 @@ const SegmentProvider: React.FC<SegmentProviderProps> = ({ activeModule, childre
};

useEffect(() => {
const disconnect = registerAnalyticsObserver();
return () => disconnect();
registerAnalyticsObserver();
return () => {
observer?.disconnect();
observer = undefined;
};
}, []);

useEffect(() => {
Expand Down

0 comments on commit 38b014c

Please sign in to comment.