I am trying to connect my Realtime Firebase Database to my Web App and eventually store data in it.
I keep running into the same problem when loading my HTML file. The error I get in the console is Uncaught ReferenceError: firebase is not defined
.
This is what my script looks like:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-analytics.js";
const firebaseConfig = {
apiKey: "<api key>",
authDomain: "<domain>",
databaseURL: "<db url>",
projectId: "<project id>",
storageBucket: "<bucket>",
messagingSenderId: "<id>",
appId: "<app id>",
measurementId: "<id>"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
var database = firebase.database();
var postListRef = database.ref('posts');
var newPostRef = postListRef.push();
newPostRef.set({
"post1": "testing"
});
</script>
CodePudding user response:
You're importing functions from Firebase using new v9 modular SDK syntax. In that syntax you have top-level functions like getDatabase()
, instead of objects like firebase.database()
.
The equivalent of the Realtime Database code in your snippet is:
var database = getDatabase(app);
var postListRef = ref(database, 'posts');
var newPostRef = push(postListRef);
set(newPostRef, {
"post1": "testing"
});
I recommend keeping the Firebase documentation on reading and writing data, appending data to a list, and the modular upgrade guide handy.
If you have a lot of existing Realtime Database code, you can migrate in steps by importing the compat
path first:
import firebase from 'firebase/compat/app';
import 'firebase/compat/database';