Skip to content
This repository has been archived by the owner on Nov 26, 2024. It is now read-only.

Commit

Permalink
feat(update): auto-upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
cedricpoon committed Oct 24, 2024
1 parent 62c756e commit 34df61e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
11 changes: 11 additions & 0 deletions public/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ precacheAndRoute(self.__WB_MANIFEST || [], {
maximumFileSizeToCacheInBytes: 50 * 1024 * 1024, // 50 MB
});

// Immediately take control of the page
self.skipWaiting();
self.clients.claim();

// Listen for messages from the client to skip waiting
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});

// Cache exchange rate API requests
registerRoute(
({ url }) => url.origin === 'https://open.er-api.com',
Expand Down
37 changes: 36 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState } from 'react';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import Transactions from './pages/Transactions';
Expand All @@ -7,14 +7,38 @@ import Balance from './pages/Balance';
import Navbar from './components/Navbar';
import { useDispatch } from 'react-redux';
import { fetchExchangeRates } from './redux/slices/currencySlice';
import { Snackbar, Button } from '@mui/material';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';

function App() {
const dispatch = useDispatch();
const [openSnackbar, setOpenSnackbar] = useState(false);
const [waitingServiceWorker, setWaitingServiceWorker] = useState(null);

useEffect(() => {
dispatch(fetchExchangeRates());
}, [dispatch]);

useEffect(() => {
serviceWorkerRegistration.register({
onUpdate: (registration) => {
setWaitingServiceWorker(registration.waiting);
setOpenSnackbar(true);
},
onSuccess: () => {
console.log('Service Worker registered successfully.');
},
});
}, []);

const handleUpdate = () => {
if (waitingServiceWorker) {
waitingServiceWorker.postMessage({ type: 'SKIP_WAITING' });
setOpenSnackbar(false);
window.location.reload();
}
};

return (
<Router hashType="noslash">
<Navbar />
Expand All @@ -24,6 +48,17 @@ function App() {
<Route path="participants" element={<Participants />} />
<Route path="balance" element={<Balance />} />
</Routes>
<Snackbar
open={openSnackbar}
message="A new version is available."
action={
<Button color="secondary" size="small" onClick={handleUpdate}>
Update
</Button>
}
onClose={() => setOpenSnackbar(false)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
/>
</Router>
);
}
Expand Down
6 changes: 6 additions & 0 deletions src/serviceWorkerRegistration.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export function register(config) {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

if (isLocalhost) {
// This is running on localhost. Let’s check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);

navigator.serviceWorker.ready.then(() => {
Expand All @@ -36,6 +37,7 @@ export function register(config) {
);
});
} else {
// Register service worker
registerValidSW(swUrl, config);
}
});
Expand All @@ -46,6 +48,7 @@ function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
// Listen for updates to the service worker.
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
Expand Down Expand Up @@ -74,6 +77,7 @@ function registerValidSW(swUrl, config) {
}

function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
Expand All @@ -83,12 +87,14 @@ function checkValidServiceWorker(swUrl, config) {
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
Expand Down

0 comments on commit 34df61e

Please sign in to comment.