Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active December 31, 2019 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidgilbertson/9f37fa79449160be4798e4cd22b4ee5f to your computer and use it in GitHub Desktop.
Save davidgilbertson/9f37fa79449160be4798e4cd22b4ee5f to your computer and use it in GitHub Desktop.
import cab from './cab.js'; // the file from above
const getOrCreateProgressData = async () => {
// Get the ID from the URL
const url = new URL(document.location);
const existingId = url.searchParams.get('id');
// If there was an ID, fetch the associated data
if (existingId) {
const readResponse = await cab.read(existingId);
return {id: existingId, data: readResponse.data};
}
// If there was no ID, create a new record
const initialData = {scrollPos: 0};
const createResponse = await cab.create(initialData);
// Put the new ID in the URL
url.searchParams.set('id', createResponse.id);
window.history.replaceState('', null, url.href);
return {id: createResponse.id, data: initialData};
};
// Kickoff
(async () => {
const {id, data} = await getOrCreateProgressData();
// If there was a scroll position, apply that now
if (data.scrollPos !== 0) window.scrollY = data.scrollPos;
// And keep the database up to date with the scroll position
window.addEventListener('scroll', () => {
cab.update(id, {scrollPos: window.scrollY});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment