firebase.database.ref is not a function error - javascript

I am trying to read/write data from my database, but I always get this error:
firebase.database.ref is not a function error
Here is how I have included firebase into a project:
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>
then:
<script>
var config = {
...
};
firebase.initializeApp(config);
</script>
The Firebase Auth works correctly. But when I do this:
function insertUser(user,name) {
var ref = firebase.database.ref();
ref.collection("users").doc(user.uid).set({
uid: user.uid,
email: user.email,
name: name
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
I get error above. What am I doing wrong?

database() is a method so change it to the following:
var reference = firebase.database().ref();
Also better not to have same variable and method name.

I also get a database function not found issue with latest firebase library. After researching what I found is, It is due to Javascript I am importing for the database:
Previously I was using below script, Which was not working:
<script src="https://www.gstatic.com/firebasejs/7.16.0/firebase-app.js"></script>
After removing -app from the script URL, it start working:
<script src="https://www.gstatic.com/firebasejs/7.16.0/firebase.js"></script>
Hope this will be helpful for others.

If you are importing firestore (database) module into the some React component make sure you will import "firebase/database" and export export const firestore = app.database() in main firebase file
Firebase.tsx
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/database"
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
})
export const firestore = app.database()
export const auth = app.auth()
export default app
myComponent.tsx
import React from "react";
import {firestore} from '../../../Firebase'
export default function Home() {
const db = firestore.refFromURL("https://<project>.firebaseio.com")
return (
...
)
}

I ran into the same problem. I just added this CDN
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-database.js"></script>

Related

Firebase: No Firebase App '[DEFAULT]' has been created - can't solve

I started looking into authentication and installed firebase using Node.js, then took the CDN links from the documentation. It worked once on saturday then hasnt worked since.
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
This is the current look of the file that handels logging in.
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js';
const firebaseConfig = {
apiKey: 'AIzaSyBfb3L9WKUf7qhVyzxpxKBRWUWbcMohUxY',
authDomain: 'study-track-7df2d.firebaseapp.com',
projectId: 'study-track-7df2d',
storageBucket: 'study-track-7df2d.appspot.com',
messagingSenderId: '1015802748429',
appId: '1:1015802748429:web:e7884ea90aec8d73d63f44',
measurementId: 'G-RPCPGGCFV1',
};
const app = initializeApp(firebaseConfig);
const btnCreate = document.querySelector('.create-account');
function googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(result =\> {
const user = result.user;
console.log(user);
})
.catch(console.log);
}
btnCreate.addEventListener('click', function (e) {
googleLogin();
});
These are the two CDN calls from the HTML
<script type="module" src="https://www.gstatic.com/firebasejs/9.16.0/firebase-app-compat.js"></script>
<script type="module" src="https://www.gstatic.com/firebasejs/9.16.0/firebase-auth-compat.js"></script>

How to read/retrieve data from Firebase using Javascript

I am trying to get my datas from firebase with console log but i am getting an error.
The error is: image
This is my database: https://i.stack.imgur.com/A1zYm.png
<script type="module">
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import {
getDatabase,
set,
ref,
update
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
const firebaseConfig = {
apiKey: ,
authDomain: ,
databaseURL: ,
projectId: ,
storageBucket: ,
messagingSenderId: ,
appId: ,
measurementId:
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth();
const firebaseRef = firebase.database().ref("Users");
firebaseRef.once("value", function(snapshot) {
snapshot.forEach(function(element) {
console.log(element);
})
});
</script>
You're trying to use the old v8 syntax with Firebase SDK 9, which won't work. You'll either have to use the new modular syntax, or import the older SDKs or the compatibility versions on v9.
In v9 syntax, getting a reference to and reading a value from the database is done with:
import { getDatabase, ref, get } from "firebase/database";
...
const database = getDatabase();
const firebaseRef = ref(database, "Users");
get(firebaseRef, function(snapshot) {
snapshot.forEach(function(element) {
console.log(element);
})
});
For more examples, see the Web version 9 (modular) tabs in the documentation I linked above, and the upgrade guide specifically the section on upgrading with the compat libraries.

httpsCallable is not defined when using Firebase Cloud Functions

For the past week I've been trying to setup Firebase Cloud Functions, but have been unable to import the dependencies needed.
This is in my script.js file, my main code:
import firebase from "firebase/app"
require("firebase/functions");
const testFunction = httpsCallable(functions, 'testFunction')
That returns this error:
script.js:7 Uncaught ReferenceError: httpsCallable is not defined
at Object.parcelRequire.script.js.firebase/app (script.js:7)
at newRequire (script.75da7f30.js:47)
at script.75da7f30.js:81
at script.75da7f30.js:120
In my index.html, I have this:
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-functions.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-analytics.js"></script>
<script>
const firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXX-XXXXX.firebaseapp.com",
databaseURL: "https://XXXXX-XXXXX-default-rtdb.firebaseio.com",
projectId: "XXXXX-XXXXX",
storageBucket: "XXXXX-XXXXX.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXXXXX:web:XXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
firebase.analytics()
</script>
What am I missing?
Edit: To upgrade to the new version of Firebase, I removed the script references in my html, did "npm i firebase#9.1.3" in my project folder, moved everything to my script.js file, and this is what it looks like now. But I still get the httpsCallable is not defined error, so the version didn't seem to affect it.
import firebase from "firebase/compat/app"
import 'firebase/compat/functions'
import 'firebase/compat/auth'
import 'firebase/compat/analytics'
import 'firebase/compat/database'
const firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXX-XXXXX.firebaseapp.com",
databaseURL: "https://XXXXX-XXXXX-default-rtdb.firebaseio.com",
projectId: "XXXXX-XXXXX",
storageBucket: "XXXXX-XXXXX.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXXXXX:web:XXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
firebase.analytics()
When using the legacy namespaced syntax (<v8 & v9 compatibility-mode), use:
import firebase from "firebase/compat/app" // just firebase/app in <v8
import 'firebase/compat/functions' // just firebase/functions in <v8
const testFunction = firebase.functions().httpsCallable('testFunction')
testFunction({ /* data */ })
.then((result) => { /* ... */ })
.catch((err) => { /* ... */ })
For the modern modular syntax (v9+), use:
import { getFunctions, httpsCallable } from 'firebase/functions'
const testFunction = httpsCallable(getFunctions(), 'testFunction')
testFunction({ /* data */ })
.then((result) => { /* ... */ })
.catch((err) => { /* ... */ })
These are documented here.

how to solve const auth not defined?

i want to use firebase authentication, so i declared a constant named auth in my html body script and i wanted to use it in my auth.js file but it say it's not defined and i want to know how to solve the probleme.
this is the code i wrote:
this is the code in my html file:
<!-- Firebase -->
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js";
// TODO: Add SDKs for Firebase products that you want to use
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric",
authDomain: "auth-project-38aaa.firebaseapp.com",
projectId: "auth-project-38aaa",
storageBucket: "auth-project-38aaa.appspot.com",
messagingSenderId: "431888894254",
appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf",
measurementId: "G-6BBPCJ3814"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth(app);
const db = getFirestore(app);
</script>
<!-- JS -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/auth.js"></script>
and this is the code in my auth.js:
const signUpForm = document.querySelector('#register-form');
signUpForm.addEventListener('submit', (e) => {
e.preventDefault();
// get user info
const name = signUpForm['name'].value;
const email = signUpForm['email'].value;
const pass = signUpForm['pass'].value;
const rePass = signUpForm['re_pass'].value;
const agreeTerm = signUpForm['agree-term'].value;
console.log(name, email, pass, rePass, agreeTerm);
// sign up the user
auth.createUserWithEmailAndPassword(email, pass).then(cred => {
console.log(cred);
});
});
The auth.createUserWithEmailAndPassword is for the Firebase SDK v8 and earlier, or for compat mode in v9.
The new syntax is according to the documentation on creating a user:
createUserWithEmailAndPassword(auth, email, pass).then(cred => {
...
});

Could not link another auth method - firebase auth

I am signing in user using mobile number and then i want him to enter email and password later. (after logging in)
I am trying to link email,password Auth method to current PhoneAuth method.
But it's giving me an error:
Cannot read property 'link' of undefined
Here is code:
import { firebaseAuth,fire, messaging } from '../../config/constants';
var credential = fire.auth.EmailAuthProvider.credential(email, password);
fire.auth.currentUser.link(credential).then(function(user) {
console.log("Account linking success", user);
}, function(error) {
console.log("Account linking error", error);
});
And in config/constants
import firebase from 'firebase'
require("firebase/firestore");
const config = {
apiKey: "AIzxxxxxxxxxxxxxxxxxxKXI",
authDomain: "payxxxxxxxxxxxxja1.firebaseapp.com",
databaseURL: "https://payxxxxxxxxxxja1.firebaseio.com",
projectId: "payxxxxxxxxxxxxja1",
storageBucket: "payxxxxxxxxxxxja1.appspot.com",
messagingSenderId: "281xxxxx5xxxxx6"
}
firebase.initializeApp(config)
export const fire = firebase
export const ref = firebase.database().ref()
export const firebaseAuth = firebase.auth
export const messaging = firebase.messaging();
I think something is wrong with fire.auth or fire.auth()
Thanks
link has been removed in favor of linkWithCredential starting with Firebase JS version 4.0.0: https://firebase.google.com/support/release-notes/js#4.0.0
Also make sure the current user is ready:
firebase.auth().onAuthStateChange(user => {
if (user) {
// currentUser is not null.
} else {
// currentUser is null.
}
});

Categories

Resources