From cbe421ee23f323a6430106fd08eb4e45c0dab7a4 Mon Sep 17 00:00:00 2001 From: Christine Legge Date: Wed, 13 Apr 2022 13:53:54 -0400 Subject: [PATCH] fix: Reload the app when there is a javascript error and a new version of the app (#3715) * reload the app when encountering a javascript error if there is an update * remove console.logs * Add more comments --- src/components/ErrorBoundary/index.tsx | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/components/ErrorBoundary/index.tsx b/src/components/ErrorBoundary/index.tsx index c8b19bdaf5..015d3d1790 100644 --- a/src/components/ErrorBoundary/index.tsx +++ b/src/components/ErrorBoundary/index.tsx @@ -49,6 +49,13 @@ type ErrorBoundaryState = { const IS_UNISWAP = window.location.hostname === 'app.uniswap.org' +async function updateServiceWorker(): Promise { + const ready = await navigator.serviceWorker.ready + // the return type of update is incorrectly typed as Promise. See + // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/update + return ready.update() as unknown as Promise +} + export default class ErrorBoundary extends React.Component { constructor(props: unknown) { super(props) @@ -56,6 +63,24 @@ export default class ErrorBoundary extends React.Component { + // We want to refresh only if we detect a new service worker is waiting to be activated. + // See details about it: https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle + if (registration?.waiting) { + await registration.unregister() + + // Makes Workbox call skipWaiting(). For more info on skipWaiting see: https://developer.chrome.com/docs/workbox/handling-service-worker-updates/ + registration.waiting.postMessage({ type: 'SKIP_WAITING' }) + + // Once the service worker is unregistered, we can reload the page to let + // the browser download a fresh copy of our app (invalidating the cache) + window.location.reload() + } + }) + .catch((error) => { + console.error('Failed to update service worker', error) + }) return { error } }