Home > other >  Syntax to run localstorage.setItem and localstorage.getItem asynchronously
Syntax to run localstorage.setItem and localstorage.getItem asynchronously

Time:01-06

I need assistance with the syntax of wrapping these functions in promises/async/await in order to make them asynchronous.

I'm trying to implement the solution provided here: Is any solution to do localstorage setItem in asynchronous way in javascript but I'm not sure how to implement .then() when my setItem function is already triggering a separate event.

running localStorage.setItem in setSelectedPage() triggers an event that that runs updateTable(). Because localstorage is synchronous, the getPages is returning a value before the setItem has written it. I need the setSelectedPage function to complete before the getPages executes.

function setSelectedPage(pages){
  window.localStorage.setItem('pages', JSON.stringify(pages)) //Triggers an event that runs updateTable
}

function updateTable(){
  //DOES STUFF
  var pages = getPages()
  //DOES MORE STUFF
}

function getPages(){
  var pages = localStorage.getItem("pages")
  return pages
}

Thanks in advance.

CodePudding user response:

Answering since I could not find a good dupe

There is no need to read from localStorage more than once on page load. from then on, you only store in the local variable and write that to localStorage

let storedPages = localStorage.getItem("pages") || `[]`;
let pages = JSON.parse(storedPages);
window.addEventListener("DOMContentLoaded", () => {
  const someButton = document.getElementById("savepages");
  const savePages = () => localStorage.setItem('pages', JSON.stringify(pages));
  const updateTable = () => {
    //DOES STUFF
    // pages are available here too
    pages.push("somepages");
    savePages(); // when necessary
    //DOES MORE STUFF
  };
  someButton.addEventListener("click",savePages); // also saves the pages to localstorage
});
  • Related