googlecodelabs / chrome-es2015

How to build your first ES2015/ES6 app
https://codelabs.developers.google.com/codelabs/chrome-es2015/
Apache License 2.0
18 stars 33 forks source link

Date parsing console errors caused by default sticky notes #6

Open acadams opened 6 years ago

acadams commented 6 years ago

This if (this.id) check at like 108 is only checking for the existence of an id, and not if the id is an integer, which is throwing an error for the default stickies. I can't find where the default sticky values are created, so I'd suggest doing a NaN check on the parseInt(this.id) and using that boolean in the if/else block.

jdmb77 commented 6 years ago

I fixed this by testing for numeric in the id. I am also deleting the default notes as they do not contain a numeric id. Hope it helps.


//** Fix#1 In displayNote delete note if id is not numeric
displayNote(key, message) {
    let note = document.getElementById(key);

    // If no element with the given key exists we create a new note.
    if (!note) {
      note = document.createElement('sticky-note');
      note.id = key;
      this.notesContainer.insertBefore(note, this.notesSectionTitle.nextSibling);
    }
    // If the message is null or id is not numeric we delete the note.
    let testIfNum = /^\d+$/.test(key);
    if (!message || !testIfNum) {
      return note.deleteNote();
    }
    note.setMessage(message);
  }

//** Fix2 in attributeChangedCallback again making sure id is numeric before applying date

attributeChangedCallback(attributeName) {

    if (attributeName == 'id') {
      let date;

      let testIfNum = /^\d+$/.test(this.id);

      if (testIfNum) {
        date = new Date(parseInt(this.id));
      }

      let dateFormatterOptions = {day: 'numeric', month: 'short'};
      let shortDate = new Intl.DateTimeFormat("en-US", dateFormatterOptions).format(date);

      this.dateElement.textContent = `Created on ${shortDate}`;
    }
  }