DEV Community

Discussion on: Local storage question

Collapse
raduman profile image
Radu Man

I think you push to "notes", and then save in localstorage "nextNotes" which is passed as an argument and never used. Push "nextNotes" to "notes" and then save in local storage

Collapse
manuelalonge profile image
Manuel Alonge Author

Hi, I have tried with your suggestion but I'm getting the same result. I will think about it a little bit more.

import {localStorage} from './local-storage/local-storage';

document.addEventListener('DOMContentLoaded', () => {
  const listItemElement = document.querySelector('.notepad__list');
  const inputElement = document.querySelector('.notepad__input');

  inputElement.addEventListener('keyup', (event) => {
    if (event.keyCode === 13) {
      addItem(event.target.value, listItemElement);
      event.target.value = null;
    }
  })
});

function addItem(text, list) {

  const el = document.createElement('li');
  const textNode = document.createTextNode(text);
  const nextNotes = [];
  el.appendChild(textNode);
  el.classList.add('notepad__item');
  list.appendChild(el);

  // retrieve the notes that are already in localstorage
  const notes = JSON.parse(localStorage.get('notes'));  
  // setting the notes array JSON into localStorage
  localStorage.set('notes', JSON.stringify(nextNotes));
  // pushing your new note into the notes array - mutation
  notes.push(nextNotes);

}