Saturday, 8 October 2022

firebase javascript shows errors if used outside the head tag

I am using Firebase to work with Firestore database. I am just inserting a document in a collection by the method setDoc. It works if I use it inside the head tag. But if I use it outside the head tag, it shows errors. The complete code follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Firebase app</title>

    <script type="module">

  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js";

  import { getFirestore,collection, addDoc, getDocs, doc, setDoc } from "https://www.gstatic.com/firebasejs/9.10.0/firebase-firestore.js"; 

  const firebaseConfig = {
    apiKey: ".....",
    authDomain: "......firebaseapp.com",
    projectId: "flutter0000",
    storageBucket: "flutter777.appspot.com",
    messagingSenderId: "8888115",
    appId: "1:9888......"
  };
  const app = initializeApp(firebaseConfig);

  const db = getFirestore(app);




  await setDoc(doc(db, "cities", "Cus11"), {
    name: "111Los Angeles",
    state: "CA",
    country: "USA"
  });



  </script>

</head>
<body>


<h1>FIREBASE APP</h1>


  <!-- <script type="module"> -->
    <script>
  
  
  await setDoc(doc(db, "cities", "Cus222"), {
  name: "111Los Angeles",
  state: "CA",
  country: "USA"
});

</script>
</body>
</html>

The setDoc method inside head tag works. But inside the body tag , the setDoc shows the following error in the console:

Uncaught SyntaxError: await is only valid in async functions, async generators and modules test.php:50:2

If I use <script type="module"> instead of just <script> inside the body tag, the following error shows up in the console:

Uncaught ReferenceError: setDoc is not defined

How to make the code work inside the body tag i.e. outside the head tag ?



from firebase javascript shows errors if used outside the head tag

No comments:

Post a Comment