Transform the data from firestore into a string format for presentation within the inner HTML

I am currently working on displaying my data within a <p> element but I'm facing some challenges. I have been able to retrieve the data and log it in the console, however, when trying to display it further than just the document id, errors are being thrown

 <script>
        // Import the necessary functions from the required SDKs
        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) => {
      // Ensure that doc.data() is not undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
      
      document.getElementById('data').innerHTML = doc.data();
    });
    
      });
      
    
        </script>
    <p id="data">LOADING...</p>

Answer №1

Instead of using a forEach loop on querySnapshot to display data, consider this alternative approach:

const items = querySnapshot.docs.map(x => ({id: x.id, data: x.data()}))
const resultString = JSON.stringify(items, null, 2);
document.getElementById('data').innerText = resultString;

You can also enhance the presentation by creating a function that generates HTML markup for each item:

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;

Remember to change your <p> tag to <div> for proper formatting.

https://codesandbox.io/s/kind-rgb-6b33vo?fontsize=14&hidenavigation=1&theme=dark

Note: If using codesandbox, remember to "reload" the built-in browser with button after making any changes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to utilize Angular without the need for Node.js?

In our project, we have been utilizing Django as our server framework and incorporating JavaScript for client-side scripting. As we transition to Angular4, we are considering the necessity of running a separate node.js server alongside our current Django ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Synchronizing Vuetify Carousel with dynamic route parameters

I'm facing an issue where the v-carousel value does not sync correctly with a route parameter using a computed property. Despite waiting for the mounted hook, the carousel seems to emit its own input and disregard the initial value from the route para ...

Sending an error from one asynchronous function to another

I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function. Unfortunately, I've been unable to successfu ...

clearing the value of an option in a select dropdown that is constantly updating

Is there a way to customize this code snippet: https://jsfiddle.net/nn83qf3y/ to display the '--None--' selections as <option value="">--None--</option> instead of <option value="--None--">--None--</option> Appreciat ...

Steps for launching an audio fileHow to start playing an audio

I am trying to automatically play an audio file audio when the window opens by using the playaudio() function. How can I achieve this? window.onload = function(playAudio();) var audio = new Audio("https://s3.amazonaws.com/audio-experiments/examples/el ...

Gather keyboard information continuously

Currently working with Angular 10 and attempting to capture window:keyup events over a specific period using RXJS. So far, I've been facing some challenges in achieving the desired outcome. Essentially, my goal is to input data and submit the request ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

JSF CommandLink malfunctions on Firefox when reRendering an entire form

I am currently working on a JSF 1.2 application (Sun RI, Facelets, Richfaces) that was previously designed only for IE6 browsers. However, we now need to extend our support to include Firefox as well. On one of the pages, there is a form with a button tha ...

What is the process of overriding methods in a function-based component in React?

Overriding in a parent component works when it is a class-based component // Parent Button Class class Button extends React.Component { createLabel = () => { return <span>{this.props.label}</span>; }; render() { return <butt ...

Include information from one source into another source

I am new to Firebase and I am trying to figure out how to transfer data from one real-time database reference to another. Here is an image of what I am trying to achieve: https://i.sstatic.net/nymgY.png In other words, I want to move the record (x) from ...

Transmit the data through AJAX to a node express server

I have been trying to use AJAX to send data to a node express server, but I am facing difficulties in catching the data using express. I want to know how to properly catch the data using express. Here is the code in my NODE file, but nothing seems to be ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

What is the best way to determine the click position on a square-shaped element?

Is there a way to retrieve the precise position of a square element when it is clicked on? ...

Is it possible to utilize super class methods as decorator methods in Typescript?

I'm working on a project where I aim to create an easily extendible decorator factory, and achieving this would be a great accomplishment. The main goal is to utilize the methods of a superclass as decorators for properties in subclasses. This is ty ...

Outputting data stored in Firestore object

Is there a way to display the content of a Firestore object in Angular Firebase? I am working on a project where I need to retrieve and print the name of a document stored in Firestore. In my Firestore database, I have a parent collection called "nforms" w ...

Refreshing knockout viewModel with the mapping plugin is a great way to update the data

I'm attempting to refresh a small widget using knockout and the mapping plugin. Below is the code I have written so far: var AppViewModel = function (data, total, qty) { var self = this; self.Products = ko.mapping.fromJS(data, {}, this); ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...