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

时间:2019-06-01 14:13:13

标签: javascript local-storage

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

e.g 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();
});

0 个答案:

没有答案
相关问题