简体   繁体   中英

convert firestore data to string to display, in inner html

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>

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 class="card">
    <div class="container">
      <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> .

编辑 kind-rgb-6b33vo

Note: in codesandbox you will need to "reload" built-in browser with button if you change something in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM