0

How can I fix this? I have no idea what event loops, promises, async or await are. You can send me a link to an explanation, or just write me an explanation. However, this is not the main issue. The issue is that I am trying to get firebase data in a function starting on line 38, and I am getting [Object object] instead of the data. But, if I look into the firebase console, it's giving me [Object Promise] Here is the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="i"></p>
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
        import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-analytics.js";
        import { getDatabase, ref, set, get, child} from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/docs/web/setup#available-libraries
      
        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
          apiKey: "AIzaSyCnfB3Tfu9bo7PyEvhB1ZAPBbit7ZWm9D8",
          authDomain: "square-1cdce.firebaseapp.com",
          projectId: "square-1cdce",
          storageBucket: "square-1cdce.appspot.com",
          messagingSenderId: "82191280296",
          appId: "1:82191280296:web:45e62faffbb7e8a94cfa9d",
          measurementId: "G-NT53HS3WE9"
        };
      
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        const analytics = getAnalytics(app);
        const db = getDatabase()
        const dbRef = ref(getDatabase());
        var data={};
        var x=prompt("Message:")
get(child(dbRef, "text")).then((snapshot) =>function(){
  if (snapshot.exists()) {
    data=snapshot.val()
  } else {
    data="No data available"
  }
}).catch((error) => {
  console.error(error);
});
        set(ref(db, 'text/'), {
          texts: get(ref(db, 'text/'))+"<br>"+x
        });
        document.getElementById("i").innerHTML= data;
        </script>
</body>
</html>

Ps. I am a ten-year-old learning javascript. My father signed me up for classes.

Pss. I made the read and write values in the rules true, so anybody can change the data with this code.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Calling the Firebase API is an asynchronous call, because it may take some time. Instead of blocking the app, your main code continues while the data is being loaded, and the `document.getElementById("i").innerHTML= data` runs before the data is loaded. When the data is available, your callback runs. For this reason, any code that needs the data from the database needs to be inside the callback, or be called from there. Also see: https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 – Frank van Puffelen Feb 22 '22 at 05:09
  • First of all, I would avoid publishing ANY credentials here. Also before you removed this question - have a look at this line ```get(child(dbRef, "text")).then((snapshot) =>function(){``` Usually in "then" function is expected, not a function that returns a function... So try to change to ```.then(function(snapshot) {``` or ```.then((snapshot) => {``` – Alexander B. Feb 22 '22 at 05:14

1 Answers1

0

You're making the write more complication than needed.

set(ref(db, 'text/'), {
  texts: get(ref(db, 'text/'))+"<br>"+x
      //  This is not needed       
});

To write the value of x to the database, you can do:

set(ref(db, 'text/'), {
  texts: x
});

If you want to append the value of x to the current value in the database, you'll need to use a transaction instead of set:

runTransaction(ref(db, 'text/texts'), (text) => {
  return text + "<br>" + x;
});

A better way to store multiple values is to use a list though, in which can you can append the value of x to that list with:

push(ref(db, 'text/texts'), x);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807