skip to Main Content

I’m trying to use onSnapshot to render in real time the result in my HTML, like so:

const collectionRef = collection(db, 'notes');

onSnapshot(collectionRef, (snapshot) => {    
    let notes = []
    let html = '';

    const noteList = document.querySelector('.notes');

    snapshot.docs.map(function(doc) {
      notes.push({ ...doc.data(), id: doc.id })
      const li = `
        <li>
          <div class="note-title"> ${notes.title} </div>
          <div class="note-content"> ${notes.content} </div>
        </li>
      `;
      html += li
    })

    const noteList = document.querySelector('.notes');
    noteList.innerHTML = html;
})

But all I’m getting is multiple "undefined" printed on the HTML.. I tried JSON.parse or stringify to no avail. What do I have to do to print this new populated "notes" array in the page?

PS: I can print something (e.g. the 1st title) if I use ${notes[0].title} but I’m stuck to print all values from the firebase.. I bet it’s simple.

2

Answers


  1. Chosen as BEST ANSWER

    Well, I put the notes object in a simple for loop and BOOM, it solved it (I feel dumb now, but I'm letting this here to help others) :)))

    const collectionRef = collection(db, 'notes');
    
    onSnapshot(collectionRef, (snapshot) => {       
        let notes = []
        let html = '';
    
        snapshot.docs.map(function(doc) {
    
          notes.push({ ...doc.data(), id: doc.id });
    
        });
    
        for(var i=0; i<notes.length; i++) {
          const li = `
            <li>
              <div class="note-title"> ${notes[i].title} </div>
              <div class="note-content"> ${notes[i].content} </div>
            </li>
          `;
          
          html += li;
        }
    
        console.log(notes, "NOTES");
    
        const noteList = document.querySelector('.notes');
        noteList.innerHTML = html;
    })
    

  2. You’re reading the title and content properties off of the notes array. Instead, you can use DocumentSnapshot#get:

     const li = `
      <li>
        <div class="note-title"> ${doc.get("title")} </div>
        <div class="note-content"> ${doc.get("content")} </div>
      </li>
    `;
    

    (You could also use doc.data().title and doc.data().content)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search