简体   繁体   中英

How do I display the contents of local Storage after button click without refreshing the page?

I want the contents of the local Storage to be displayed when the submit button is clicked without having to refresh the page. I don't see the changes made until I manually refresh the page

This function handles the page load. When a button is clicked it shows wrong data. The correct data is only shown when the page is manually refreshed.

const loadData = () =>
  document.querySelector('body').addEventListener('load', displayStorage());

This is the event listener that handles saving:

notesForm.addEventListener('submit', e => {
  e.preventDefault();
  const save = (sid, spost, sdate) => {
    const obj = { id: sid, post: spost, date: sdate };
    localStorage.setItem(`${sid}`, JSON.stringify(obj));
  };
  save(generateId(), post.value, dateFormat());
  loadData();
});

The loadData function is only adding an event listener. It is not displaying the data in localStorage.

Try replacing the loadData() call in the submit callback with displayStorage() .

try providing the function as a handler to be invoked by the load event. Not invoke it by yourself

const loadData = () =>
  document.querySelector('body').addEventListener('load', displayStorage);

You can try reloading the page by yourself using location.reload

notesForm.addEventListener('submit', e => {
  e.preventDefault();
  const save = (sid, spost, sdate) => {
    const obj = { id: sid, post: spost, date: sdate };
    localStorage.setItem(`${sid}`, JSON.stringify(obj));
  };
  save(generateId(), post.value, dateFormat());
  loadData();
  location.reload()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM