From ee0374957471f6f131ebfda5ef2f084764b2d920 Mon Sep 17 00:00:00 2001 From: infinite-persistence Date: Wed, 6 Apr 2022 11:26:42 +0800 Subject: [PATCH] Patch for outbrain visibility (e68bba1d) ## Issue - Due to the timer used, the script could be loaded after the path-checking useEffect ran. - Stale closure is also an issue. ## Approach Create refs for the props, and listen to `onload` as well to resolve the visibility state. --- ui/effects/use-ad-outbrain.js | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/ui/effects/use-ad-outbrain.js b/ui/effects/use-ad-outbrain.js index 1ca55f197..195ddc4b4 100644 --- a/ui/effects/use-ad-outbrain.js +++ b/ui/effects/use-ad-outbrain.js @@ -30,12 +30,26 @@ export default function useAdOutbrain(hasPremiumPlus: boolean, isAuthenticated: // when returned as false const isNotAuthenticated = isAuthenticated === false; + const propRef = React.useRef({ isAuthenticated, pathname }); + propRef.current = { isAuthenticated, pathname }; + + function resolveVisibility() { + if (window[OUTBRAIN_CONTAINER_KEY]) { + if (propRef.current.isAuthenticated) { + window[OUTBRAIN_CONTAINER_KEY].style.display = 'none'; + } else { + window[OUTBRAIN_CONTAINER_KEY].style.display = EXCLUDED_PATHS.includes(propRef.current.pathname) ? 'none' : ''; + } + } + } + React.useEffect(() => { if (!inIFrame() && isNotAuthenticated && !script) { const loadTimer = setTimeout(() => { script = document.createElement('script'); script.src = 'https://adncdnend.azureedge.net/adtags/odysee.adn.js'; script.async = true; + script.addEventListener('load', resolveVisibility); // $FlowFixMe document.body.appendChild(script); @@ -43,16 +57,10 @@ export default function useAdOutbrain(hasPremiumPlus: boolean, isAuthenticated: return () => clearTimeout(loadTimer); } - // eslint-disable-next-line react-hooks/exhaustive-deps, (on mount only) + // eslint-disable-next-line react-hooks/exhaustive-deps }, [isNotAuthenticated]); React.useEffect(() => { - if (window[OUTBRAIN_CONTAINER_KEY]) { - if (isAuthenticated) { - window[OUTBRAIN_CONTAINER_KEY].style.display = 'none'; - } else { - window[OUTBRAIN_CONTAINER_KEY].style.display = EXCLUDED_PATHS.includes(pathname) ? 'none' : ''; - } - } + resolveVisibility(); }, [isAuthenticated, pathname]); }