简体   繁体   中英

How do I get items from localStorage and display in my UI?

This is what I have tried. It works with just a small issue. Anytime I add a new item to the localStorage it multiplies the items when displaying it until I refresh the page

const displayStorage = () => {
  let values = [],
    keys = Object.keys(localStorage),
    i = keys.length;
  while (i--) {
    if (keys[i] === 'theme') continue;
    values.push(JSON.parse(localStorage.getItem(keys[i])));
  }
  values.reverse();
  return values.forEach(obj => showNotes(obj));
};

eg let's say I have 123 stored and I want to add 4. It returns 1231234 instead of just 1234

This is the function that handles the UI display

const showNotes = ({ id, post, date }) => {
  const noteSection = document.createElement('div');
  noteSection.classList.add('notes-container');
  const notes = document.createElement('article');
  notes.classList.add('single-note');
  notes.textContent = post.substring(0, 100);

  const viewMore = document.createElement('a');
  viewMore.classList.add('view-more');
  viewMore.textContent = '...';
  viewMore.setAttribute('title', 'View more');
  viewMore.addEventListener('click', e => {
    e.preventDefault();
    if (notes.textContent.length <= 110) {
      notes.textContent = post;
      notes.appendChild(viewMore);
      viewMore.setAttribute('title', 'View less');
    } else {
      notes.textContent = post.substring(0, 100);
      notes.appendChild(viewMore);
      viewMore.setAttribute('title', 'View more');
    }
  });

  const noteActions = document.createElement('span');
  noteActions.classList.add('note-actions');
  const deleteLink = document.createElement('a');
  deleteLink.textContent = 'Delete';
  deleteLink.setAttribute('data-id', `${id}`);
  deleteLink.addEventListener('click', deleteNote);

  const notesDate = document.createElement('aside');
  notesDate.classList.add('note-date');
  notesDate.textContent = date;
  noteActions.appendChild(deleteLink);
  notes.appendChild(viewMore);
  notes.appendChild(noteActions);
  noteSection.appendChild(notesDate);
  noteSection.appendChild(notes);
  document.querySelector('.notes').appendChild(noteSection);
};

This is the function to save

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());
  displayStorage();
});

its a simple solution but may be useful for someone, just clear items from UI, and again display them from localstorage, this will show the old and new items from localstorage.

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