Skip to content

Commit

Permalink
Merge branch 'main' into rnd-5808-sidebar-new-style-settings-gbo
Browse files Browse the repository at this point in the history
  • Loading branch information
zenoachtig authored Jan 7, 2025
2 parents 7104adc + 12f25d8 commit 58d3b73
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/quiet-oranges-provide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'gitbook': patch
---

Fix dynamic tabs infinite loop
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ let globalTabsState: TabsState = (() => {
const stored = localStorage.getItem('@gitbook/tabsState');
return stored ? (JSON.parse(stored) as TabsState) : { activeIds: {}, activeTitles: [] };
})();

const listeners = new Set<() => void>();

function useTabsState() {
Expand All @@ -30,13 +31,13 @@ function useTabsState() {

const getSnapshot = useCallback(() => globalTabsState, []);

const setTabsState = (updater: (previous: TabsState) => TabsState) => {
const setTabsState = useCallback((updater: (previous: TabsState) => TabsState) => {
globalTabsState = updater(globalTabsState);
if (typeof localStorage !== 'undefined') {
localStorage.setItem('@gitbook/tabsState', JSON.stringify(globalTabsState));
}
listeners.forEach((listener) => listener());
};
}, []);
const state = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
return [state, setTabsState] as const;
}
Expand Down
21 changes: 9 additions & 12 deletions packages/gitbook/src/components/Insights/InsightsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,6 @@ export function InsightsProvider(props: InsightsProviderProps) {
| undefined;
}>({});

/**
* Get the visitor ID and store it in a ref.
*/
React.useEffect(() => {
getVisitorId().then((visitorId) => {
visitorIdRef.current = visitorId;
});
}, []);

/**
* Synchronously flush all the pending events.
*/
Expand Down Expand Up @@ -194,13 +185,19 @@ export function InsightsProvider(props: InsightsProviderProps) {
},
);

// When the page is unloaded, flush all events
/**
* Get the visitor ID and store it in a ref.
*/
React.useEffect(() => {
window.addEventListener('beforeunload', flushEventsSync);
getVisitorId().then((visitorId) => {
visitorIdRef.current = visitorId;
// When the page is unloaded, flush all events, but only if the visitor ID is set
window.addEventListener('beforeunload', flushEventsSync);
});
return () => {
window.removeEventListener('beforeunload', flushEventsSync);
};
}, [flushEventsSync]);
}, []);

return (
<InsightsContext.Provider value={trackEvent}>
Expand Down

0 comments on commit 58d3b73

Please sign in to comment.