I Want to display my data in this <p>
element but I don't know how. I can get it and then console log it but that's it right now, I got it to display document id but when I go further than that it throws errors
<script>
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";
import { onMount } from 'svelte';
import { collection, addDoc, onSnapshot, getDocs, doc, getDoc, query, where } from "firebase/firestore";
let db;
onMount(async() => {
const firebaseConfig = {
////
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
db = getFirestore(app);
const querySnapshot = await getDocs(collection(db, "songs"));
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
document.getElementById('data').innerHTML = doc.data();
});
});
</script>
<p id="data">LOADING...</p>
CodePudding user response:
Instead of
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
document.getElementById('data').innerHTML = doc.data();
});
you can use this:
const items = querySnapshot.docs.map(x => ({id: x.id, data: x.data()}))
const resultString = JSON.stringify(items, null, 2);
document.getElementById('data').innerText = resultString;
Also, add this style to your <p>
: style="white-space: pre-wrap;"
Updates: for something more fancy you can create a function for each of your items that will return some html markup.
function getRecordTemplate(record) {
return `
<div >
<div >
<h1><b>${record.data.artist}</b></h1>
<h5>Id: ${record.id}</h5>
<p>Song: ${record.data.song}</p>
</div>
</div>
`;
}
const blockNodes = items.map((x) => getRecordTemplate(x)).join("");
document.getElementById('data').innerHTML = blockNodes;
BUT: Change your <p>
to <div>
.
Note: in codesandbox you will need to "reload" built-in browser with button if you change something in it.