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>
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';
Related
I'm new to firebase/javascript/html coding, so I really don't know what I'm doing.
But I was following a tutorial on how to make firebase work with a WebGL Unity build and got stuck here:
html code
`
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "apikey",
authDomain: "authDomain.firebaseapp.com",
databaseURL: "databaseURL.firebasedatabase.app",
projectId: "projectId",
storageBucket: "storageBucket.appspot.com",
messagingSenderId: "messagingSenderId",
appId: "appId",
measurementId: "G-measurementId"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
</script>
jslib script:
PostJSON: function(path, value, objectName, callback, fallback) {
var parsedPath = Pointer_stringify(path);
var parsedValue = Pointer_stringify(value);
var parsedObjectName = Pointer_stringify(objectName);
var parsedCallback = Pointer_stringify(callback);
var parsedFallback = Pointer_stringify(fallback);
try {
firebase.database().ref(parsedPath).set(JSON.parse(parsedValue)).then(function(unused) {
unityInstance.Module.SendMessage(parsedObjectName, parsedCallback, "Success: " + parsedValue + " was posted to " + parsedPath);
});
} catch (error) {
unityInstance.Module.SendMessage(parsedObjectName, parsedFallback, JSON.stringify(error, Object.getOwnPropertyNames(error)));
}
}
`
Every time I try to post a value it says: firebase is not defined.
What am I doing wrong?
You're mixing the namespaced firebase.database() syntax of Firebase SDK versions 8 and before with the modular initializeApp syntax of Firebase SDK versions 9 and later, which doesn't work.
Since you're initializing the modular SDK, your database access code should use the new modular syntax too:
import { getDatabase, ref, set } from "firebase/database";
const db = getDatabase();
set(ref(db, parsedPath), JSON.parse(parsedValue)).then(function(unused) {
unityInstance.Module.SendMessage(parsedObjectName, parsedCallback, "Success: " + parsedValue + " was posted to " + parsedPath);
});
To learn how to upgrade the code, have a look at the migration guide and keep the Firebase documentation handy as all code samples in there have variants for both syntaxes such as in this page on reading and writing data.
I am connecting javascript & firebase but got this issue,
I am facing this issue I switched networks as well but it doesn't work,
firebase v9
javascript
package file: webpack, webpack-cli
filename: index.js
import { initializeApp } from 'firebase/app';
import {getFirestore, collection, getDocs} from 'firebase/firestore';
const firebaseConfig = {
apiKey: ...,
authDomain: ...,
projectId: ...,
storageBucket: ...,
messagingSenderId: ...,
appId: ...
};
// initialize application
const app = initializeApp(firebaseConfig, {
experimentalForceLongPolling: true,
useFetchStreams: false
});
// initialize serivice
const db = getFirestore();
// collection ref
const colRef = collection(db, 'books');
// get collection data
getDocs(colRef)
.then(snapshot => {
console.log(snapshot.docs)
})
Thanks in advance!
To connect to the firestore applications you need to check that your internet connection is very well,
I encounter that the internet I was working on was not well enough, I changed the connection again and restart the system,
It resolved the issue!
i need to store some simple data on the firebase realtime database, i've connected my app to the firebase realtime database, and imported all the requirments in the javascript file, but whenever my code is done, i check the realtime database and find that nothing is stored, i've followed many tutorials on youtube, even the firebase tutorial on youtube, but the mentionned problem stays, the realtime database stays empty as if i didn't write any code.
Here is the javascript code :
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set } from 'firebase/database';
const firebaseConfig = initializeApp({
apiKey: "AIzaSyChK5qg7AJi0_AZQAc2iWnvDVJjyJvz5iI",
authDomain: "mycoolapp-4373a.firebaseapp.com",
databaseURL: "https://mycoolapp-4373a-default-rtdb.firebaseio.com",
projectId: "mycoolapp-4373a",
storageBucket: "mycoolapp-4373a.appspot.com",
messagingSenderId: "895684408479",
appId: "1:895684408479:web:3341db270dcd768e085eaa"
});
const app = initializeApp(firebaseConfig);
function writeUserData(userId, username, email, message) {
const db = getDatabase();
const reference = ref(db, 'users/' + userId);
set(reference, {
username: username,
email: email,
message: message
});
}
writeUserData("andrew","andrew__8","andrew#gmail.com", "hey..i'm andrew!!");
is there any other working way ?
I am trying to make a small database system for my client that will capture his website's registered users name and there spent amount. Based on there spent amount he will get some gifts.
Using firebase realtime database i am able to store user spent amount but when i try to get data from database. I am getting the following Error from the line:
get(child(userDbRef, "User-ID-"+userID)):
"Uncaught (in promise) Error: Error: Client is offline."
initailData(); will work if user does not have data stored already and if the data has been stored once then runInitialFunction(); will work and get/retrieve data from database.
Here is my code
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.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
const firebaseConfig = {
apiKey: "AIzaSyAfA1HIkamXEFtDidPkpxaltDVsWpFWepE",
authDomain: "thundersmmpanel-77fb2.firebaseapp.com",
databaseURL: "https://thundersmmpanel-77fb2-default-rtdb.firebaseio.com",
projectId: "thundersmmpanel-77fb2",
storageBucket: "thundersmmpanel-77fb2.appspot.com",
messagingSenderId: "867306490186",
appId: "1:867306490186:web:93407cb6d8b0e9abe9d9b3"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
//<!--my code-->
import {getDatabase, ref, set, get, child, update}
from "https://www.gstatic.com/firebasejs/9.6.0/firebase-database.js";
const userID = {{user['id']}};
const userName = "{{user['username']}}";
const pointsDb = getDatabase();
//<!-- initial data -->
function initailData() {
set(ref(pointsDb, "User-ID-"+userID),{
UserName: userName,
InitialSpent: {{user['spent']}},
ThisRun: 1
})
.then(function(){
alert("Done");
})
.catch(function(error){
alert("Error "+error);
});
console.log("initailData");
}
function runInitialFunction() {
const userDbRef = ref(pointsDb)
get(child(userDbRef, "User-ID-"+userID)).then((snapshot)=>{
if(snapshot.exists()){
}else{
initailData();
}
});
console.log("runInitialFunction");
}
runInitialFunction();
I am doing a small project with Google authentication. Now, this is my first time doing this, so I might be doing something wrong which I am not seeing. I did the following steps:
-I went on firebase and linked my account
-I enabled google to be able to use it for authentication
-I pasted the project data in my file, as I will show in a bit
-and I put the code for the autentication
<script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyArVSWB1OYZYQJEkmc6uIi9jyfmRIW1oSk",
authDomain: "assignment-da42d.firebaseapp.com",
databaseURL: "https://assignment-da42d.firebaseio.com",
projectId: "assignment-da42d",
storageBucket: "assignment-da42d.appspot.com",
messagingSenderId: "569189156463",
appId: "",
measurementId: "G-N6D1788RXF"
};
firebase.initializeApp(firebaseConfig);
function googleSignIn(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider)
}
</script>
<button onclick="googleSignIn()">Google Sign in</button>
However, even after following multiple tutorials, using the same methods, I kept getting the error:
Uncaught TypeError: Cannot read property 'GoogleAuthProvider' of undefined
What am I doing wrong please?
I had the same issues late week and I've since solved it.
Can you point out where you include the following or some other version of the auth library?
<script src="/__/firebase/[version number]/firebase-auth.js"></script>
If that's missing you can paste it in before your code.
I installed the whole package - $ npm install --save firebase
and my config file looks like
import firebase from "firebase/app";
import "firebase/storage";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "......",
authDomain: ".....",
databaseURL: ".....",
projectId: ".....",
storageBucket: ".....",
messagingSenderId: "......",
appId: "......",
measurementId: "...."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const projectStorage = firebase.storage();
export const projectFirestore = firebase.firestore();
export const timestamp = firebase.firestore.FieldValue.serverTimestamp;
export const auth = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () =>{
auth.signInWithRedirect(provider).then(function(){
});
};
and I can call
const logIn = () => {
let ret = signInWithGoogle();
console.log(ret);
getCredentials();
}
in the navbar.