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
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) :)))
You’re reading the
title
andcontent
properties off of thenotes
array. Instead, you can useDocumentSnapshot#get
:(You could also use
doc.data().title
anddoc.data().content
)