how to solve this firebase is not defined error? - javascript

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.

Related

Could not reach Cloud Firestore backend. Connection failed 1 time. this typically indicates that your device does not have healthy Internet

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!

Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

i have been solving this issue since past 2 days but cant get any idea of how it is solved
const handleSignUp = () => {
auth
.createUserWithEmailAndPassword(email, password)
.then(userCredentials => {
console.log(userCredentials.user.uid)
const user = userCredentials.user;
console.log('Registered with:', user.email);
setDoc(doc(db, "users", "LA"), {
name: "Los Angeles",
// state: "CA",
// country: "USA"
});
})
.catch(error => alert(error.message))
}
The Firebase module is here
if it need any changes of any dependency or any version
please suggest as firebase version is 9.6.11,while firestore is of 3.4.14
// Import the functions you need from the SDKs you need
// import firebase from "firebase";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/database"
// import { getFirestore } from "#firebase/firestore";
import { getFirestore } from 'firebase/firestore'
// import { getFirestore } from 'firebase/firestore/lite'
const firebaseConfig = {
apiKey: ........................
authDomain: ........................
projectId: ........................
storageBucket: ........................
messagingSenderId: ........................
appId: ........................
};
// Initialize Firebase
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app()
}
export const auth = firebase.auth()
// export const db = firebase.firestore();
export const db = getFirestore(app)
The error indicates that you are calling setDoc() function to something that is not a DocumentReference or a CollectionReference.
You may try to get the details from the console log as to which variable reference it is hitting the above error and understand why what you are calling it on is not a valid CollectionReference or DocumentReference. Please read through the helpful documentation for Collection Reference
The function setDoc() ,writes to the document referred to by the specified DocumentReference. If the document does not yet exist, it will be created. If you provide merge or mergeFields, the provided data can be merged into an existing document.The result of this write will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.
Also check and verify that you are to call the firebase admin sdk rather than the client SDK and see if that works.
It's an AngularFire version issue, basically if you're using Angular 12, with Firebase 9 you need #angular/fire#^7.0
The compatibility table on the firebase page is key: https://github.com/angular/angularfire#angular-and-firebase-versions
I struggled with this issue for hours ?days? and it was because I had angularfire 7.4 (even 7.2 didn't work).

unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization

I'm very new to next.js, and I'm developing an API with it, side that API I want to use firebase, so I set up firebase but when I try to call it, this error appears: "unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization"
Code below.
Firebase config file
import firebase from 'firebase/app';
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "*******",
authDomain: "********",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
//if(!firebase.apps.length){
//}
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
Firestore service
import { firestore } from './firebase';
export class Firestore {
async getOne(collection, uid){
const data = await firestore.collection(`${collection}/${uid}`).get();
return await data.docs();
}
}
API page
import {Firestore} from '../../utils/firestore';
const firestore = new Firestore();
const getBanners = () => {
return firestore.getOne('settings','client');
//return data;
}
export default function Handler(req,res){
res.status(200).json({
'name':"getBanners",
'data': getBanners()
});
}
I solved this issue by adding import firebase from 'firebase/compat/app'; and also import 'firebase/compat/firestore';. And works!

Firebase is not defined when connecting to Realtime Database Web

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';

TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.firestore is not a function

Just trying to set it up firebase for the first time and I get these errors cant find any right answer to work this is my config
// Import the functions you need from the SDKs you need
import firebase from 'firebase/compat/app';
import 'firebase/firestore';
import {
initializeApp
}
from "firebase/app";
// 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: "x",
authDomain: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x",
appId: "x"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = firebase.firestore();
export {
db
};
the error I get -
TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.firestore is not a function
it shows to the line
const db = firebase.firestore();
If you want to use the compat version of firestore you need to initialize the firebaseApp also with the compat version. I would recommend using the new SDK version for both:
import { getFirestore } from "firebase/firestore";
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "x",
authDomain: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x",
appId: "x",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
export { db };
With the new SDK, you actually don't need such a file like before where you initialize your app and create the database instances. After you initialize your app with the new SDK you can just call getFirestore() without the need to have the firebaseApp for it. getFirestore() will automatically use the default app.
A realtime listener by using collection would look like this:
import { collection, onSnapshot } from "firebase/firestore";
const unsubscribe = onSnapshot(collection(db, "cities"), () => {
// Respond to data
// ...
});
// Later ...
// Stop listening to changes
unsubscribe();
When you read the Firebase docs make sure to switch to the SDK 9 version:
Try replacing this line of your code:
import 'firebase/firestore';
for this:
import 'firebase/compat/firestore';
This way you'll be using compatability api in both imports

Categories