0

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.

Josh
  • 19
  • 5
  • 3
    This is smelling of an X/Y problem. – mplungjan Jan 05 '23 at 10:54
  • 1
    You only need to do ONE getItem, when the page loads. Then from then on, update a variable in the page and write that to localStorage – mplungjan Jan 05 '23 at 10:55
  • 2
    Surely making it asynchronous won't solve anything - it seems like you are trying to get your pages before setting it - if your set triggers the update - make sure you set before you update - or pass the pages into the update so you don't need the get in the update – Pete Jan 05 '23 at 10:56
  • Thanks @mplungjan. Write that as an answer and I'll accept it. – Josh Jan 05 '23 at 11:03

1 Answers1

1

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
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236