Firebase currentUser and onAuthStateChanged - javascript

I am developing an app using react native, every time I refresh the app on the emulator in onAuthStateChanged and currentUser from firebase I get null.
I have read about waiting onAuthStateChanged to get a status update but I never do, so I guess I misconfigured something.
I am using expo 44, react 17, firebase 9.6.5 but in compat mode (planning in fully migrate later)
My first attempt of solution was trying to add persistence: firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";
import AsyncStorage from "#react-native-async-storage/async-storage";
import { firebaseConfig } from "./firebase/firebaseConfig";
firebase.initializeApp(firebaseConfig);
firebase.firestore();
firebase.functions();
firebase.storage();
firebase.auth();
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
firebase.auth().onAuthStateChanged(async (user) => {
console.log("onAuthStateChanged called: ", user);
if (user) {
await AsyncStorage.setItem('#isLoggedIn', '1');
} else {
await AsyncStorage.setItem('#isLoggedIn', '0');
}
});
export default firebase;
But I get an error:
undefined is not an object (evaluating 'this.storage.setItem')
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:5248:0 in verifyBeforeUpdateEmail
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:5420:12 in _fromIdTokenResponse
at http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:183132:41 in _set
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1414:55 in newData.some$argument_0
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:2060:1 in <global>
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:2047:30 in _isIOS
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
at node_modules/#firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
to Login I use:
userCredential = firebase
.auth()
.signInWithEmailAndPassword(data.email, this.state.password);

I had this exact same issue. I solved it by adding "firebase": "^8.9.1" to package.json, running yarn install and changing the import import firebase from "firebase" (remove all the other imports you have). Apparently selective imports have a bug in v8, but at least it works well :)

Related

service firestore is not available

I'm trying to connect to my firestore using plain javascript. (I wanna get up to speed and running for now)
index.js:
import app from './firebase.js'
import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-firestore.js'
const db = getFirestore(app)
However, this throws an error: Uncaught Error: Service firestore is not available
firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = {
// configs
};
// Initialize Firebase
let app
export default app = initializeApp(firebaseConfig);
Then I import the script in my index.html:
<!DOCTYPE html>
....
<script type="module" src="index.html"></script>
Note: I can read and write to the firestore using firebase web interface.
So if you want to use plain js (without bundlers like webpack), you would need to put your JS code into script tag like so:
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = { ... };
const app = initializeApp(firebaseConfig);
</script>
Otherwise, if you want to use it like you intended to do so, you would need to:
install a firebase package
a module bundler (e.g. webpack) to bundle the files for you
Using npm, but got the same error message.
Restarted terminal & uninstalled and reinstall firebase, then worked...not sure which one that did it though.
You need to upgrade your firestore version 9.0.0 to 9.4.0 and it work fine
import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-firestore.js";
Change your import link import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
to import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
just update the firebase version from 9.0.0 to 9.0.1

firebase.apps.length of undefined

Environment
Operating System version: Windows 11
Browser version: Chrome
Firebase SDK version: 9.0.2
Firebase Product: database
firebase.apps.length of undefined
Issue:
I dont know what happened today morning it opened my code and it shows something like
app.firestore() is not a function and shows firebase.apps.length of undefined
Code:
import * as firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app()
const db = app.firestore()
The syntax for Firebase has changed in v9, as everything is now modular/functional. You can now safely get an app with:
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
I highly recommend keeping Firebase's own documentation and this upgrade guide handy.
Alternatively, you can keep using the older syntax by using the compatibility mode of the newer SDKs, by importing from the compat path.
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
In that case the rest of your code stays unchanged.

Cannot read property 'auth' of undefined

I'm trying to use firebase-ui in a VueJS project.
My api credentials is defined in a file called config.js
export default {
apiKey: "*****",
authDomain: "*****.firebaseapp.com",
databaseURL: "https://my-project.firebaseio.com",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "73482979",
appId: "1:685818581200:web:1f5ebjnfsdjnj",
measurementId: "G-BHJK6N67PZ"
};
I am the importing the config.js file in my init.js where the whole firebase setup is done:
import config from "./config";
import firebase from "firebase";
import firebaseui from "firebaseui";
import "firebase/auth";
import "firebase/firestore";
const app = firebase.initializeApp(config);
const auth = firebase.auth();
const firestore = app.firestore();
const authUi = new firebaseui.auth.AuthUI(auth); //Error is thrown at this point
export default app;
export { auth, authUi, firestore };
However the error -> Cannot read property 'auth' of undefined' is thrown and I've been unable to move past here for a few days now. I've checked the documentation (https://firebase.google.com/docs/auth/web/firebaseui#before_you_begin), everything is done correctly and even using the latest firebaseui version "firebaseui": "4.7.0" located in package.json
Any help with how I can solve this problem?
As of Firebase 9.0.0 (August 25, 2021) it should now be
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
to use the backwards compatible interface.
See https://firebase.google.com/docs/web/modular-upgrade for the full upgrade path
I got the same problem. After few hours of trying, I solve it by edit my config like :
import firebase from 'firebase/app';
import * as firebaseui from 'firebaseui';
import 'firebaseui/dist/firebaseui.css';
If your firebase version if greater than 7, you got to import from 'firebase/app' instead of 'firebase'.
And you have to import * from 'firebaseui', instead of import only firebaseui.
and my packages.json like:
"dependencies": {
"firebase": "^8.8.0-202162022140",
"firebaseui": "^4.8.1",
},
By the way, my project is using Vue3.js.
You're importing the Firebase client JS library incorrectly. The documentation for module bundlers shows:
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
// If you are using v7 or any earlier version of the JS SDK, you should import firebase using namespace import
// import * as firebase from "firebase/app"
Don't import from "firebase". Import from "firebase/app", and be sure to observe the conventions for the version of the SDK you're using.
The documentation for firebaseui might be out of date. Consider submitting your feedback using the "send feedback" button at the top of the doc page.

How to enable `ignoreUndefinedProperties` in node js

I am developing a REST api for my application in Nodejs and Express. But each time i try to send a request I get an undefined error. Please how can i enable 'ignoreundefinedproperties'
once you import the firebase-admin sdk (in Typescript) like this
import * as firestore from "firebase-admin";
then you just need to set the setting like this :
const db = firestore.firestore();
db.settings({ ignoreUndefinedProperties: true })
If you are getting errors for calling this more than once, I recommend putting admin.firestore().settings({ignoreUndefinedProperties:true}); in the same place you have admin.initializeApp();
Here's how I did it in my Typescript project
initialize.ts:
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
admin.firestore().settings({ignoreUndefinedProperties:true});
Top of index.ts:
import './initialize.ts'
For anyone using the v9 API:
import { getFirestore, connectFirestoreEmulator, initializeFirestore } from 'firebase/firestore'; // Firebase v9+
// Must be called before getFirestore()
initializeFirestore(app, {
ignoreUndefinedProperties: true
});
const firestore = getFirestore(app);
If you're facing error (Firestore has already been initialized. You can only call settings() once) even after trying other answers, restart your IDE/VSCode and terminal. This is what worked for me.

Cannot read property 'firestore' of null when trying to initialize firebase in nuxt app

I am trying to use Firebase and Firestore in my nuxt application. I have done everything according to the documentation, but something seems to be wrong.
Obviously, if (!firebase.apps.length) evaluates to false, so app stays null, but I'm not initializing firebase from anywhere else, so this shouldn't happen
plugins/firebase.js
import firebase from "firebase";
import firestore from "firebase/firestore"; //linter says that firestore is declared but never read, which is weird, since it is.
const firebaseConfig = {
//config data of my project (not sure if I can share them, so I don't)
};
let app = null;
if (!firebase.apps.length) {
app = firebase.initializeApp(firebaseConfig);
}
export const db = app.firestore();
nuxt.config.js
plugins: ["~/plugins/firebase.js"],
layouts/default.vue
<script>
import * as firebase from "firebase/app";
</script>

Categories