React Native firebase is undefined - javascript

Hi I keep getting this error when trying to run my react-native app on expo go on my phone
TypeError: undefined is not an object (evaluating '_app.default.apps')
and the error shows it pointing to the firebase variable on line 19 in the code below in the if statement where it says firebase:
import firebase from 'firebase/app';
require('firebase/auth');
import Constants from 'expo-constants';
// Initialize Firebase
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId,
measurementId: Constants.manifest.extra.measurementId
};
let Firebase;
if (firebase.apps.length === 0) {
Firebase = firebase.initializeApp(firebaseConfig);
}
export default Firebase;
this in turn is causing I believe an Invariant violation as well.
Any help please?

FirebaseSDK changed their API in the new version 9 so now import firebase from “firebase/app” won’t work
You need to use the import { initializeApp } from 'firebase/app'; to initiate your app or import from firebase/compat/app to use the old API
Refer to https://firebase.google.com/docs/web/modular-upgrade for more about the changes and https://firebase.google.com/docs/web/setup for the new API

Related

src\firebase.js Line 20:14: 'firestore' is not defined no-undef Search for the keywords to learn more about each error

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "AIzaSyA-1CDIgbhEIzl3OuyBVj07f23bHcGdhi4",
authDomain: "netflix2-9d006.firebaseapp.com",
projectId: "netflix2-9d006",
storageBucket: "netflix2-9d006.appspot.com",
messagingSenderId: "834718120256",
appId: "1:834718120256:web:add5fc25daf4729190a2a5"
};
const fireabaseApp = firebase.initializeApp(firebaseConfig);
const db = fireabaseApp.firestore();
const auth = firestore.auth();
export {auth} ;
export default db;
this is my firebase.js file i have used latest firebase version even though i have been facing issue with firestore pls guide thank you
this is my firebase.js file i have used latest firebase version even though i have been facing issue with firestore .
can anyone guide how can i import firestore from the firebase Thank you.

Error in Firebasse"assert.ts:128 Uncaught FirebaseError: Firebase: Error (auth/invalid-api-key)

Why do I have the error that it says invalid API keys?
This is the sample .env.local
REACT_APP_apiKey=AI**************JmXMKaFQQQrRzp4Q
REACT_APP_authDomain=sample-258a7.firebaseapp.com
REACT_APP_projectId=sample-258a7
REACT_APP_storageBucket=sample-258a7.appspot.com
REACT_APP_messagingSendearId=
REACT_APP_appId=1:1014069435807:web:04390779a92d4e3a4fb1aa
In another file:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth, GoogleAuthProvider, onAuthStateChanged } from "firebase/auth";
project under its own project settings
const firebaseConfig = {
apiKey: process.env.REACT_APP_apiKey,
authDomain: process.env.REACT_APP_authDomain,
projectId: process.env.REACT_APP_projectId,
storageBucket: process.env.REACT_APP_storageBucket,
messagingSenderId: process.env.REACT_APP_messagingSenderId,
appId: process.env.REACT_APP_appId,
};
//Initializing Firebase
const app = initializeApp(firebaseConfig);
This is the error:
The Package.json:
Make sure your .env.local is placed in the root directory, and not in any subfolders like src or public. Other than that, nothing seems to be wrong with your code. Just to be safe, cross check your API key with firebase.
P.S. There's no need to hide your firebase public API key, its going to be visible in your app to the general public anyway.

firebase working but firebase.auth() not working in Vue.js

I ran
npm i firebase
and have
import firebase from 'firebase/compat/app'
but when i run
console.log(firebase.auth())
I get an error message of
app.js:280 Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
at app (firebaseNamespaceCore.ts?1484:102:1)
at Object.serviceNamespace [as auth] (firebaseNamespaceCore.ts?1484:152:1)
at eval (HelloWorld.vue?e90b:24:1)
at Module../node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/HelloWorld.vue?vue&type=script&lang=js (app.js:30:1)
at __webpack_require__ (app.js:277:33)
at fn (app.js:517:21)
at eval (HelloWorld.vue?vue&type=script&lang=js:5:213)
at Module../src/components/HelloWorld.vue?vue&type=script&lang=js (app.js:140:1)
at __webpack_require__ (app.js:277:33)
at fn (app.js:517:21)
However, when I just run console.log(firebase) I get correct data output in console. I have also setup firebase correctly as documented here but firebause.auth() is still not working. I am working in Vue3 but I don't think that part matters, still trying to find a solution.
I am currently trying to get firebaseUI to work and this is the step I am getting stuck in. Once I'm able to get firebause.auth() to work, I'll be able to initialize the firebaseUI widget by running:
var ui = new firebaseui.auth.AuthUI(firebase.auth());
my ./src/firebaseConfig.js code:
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "code",
authDomain: "code",
projectId: "code",
storageBucket: "code",
messagingSenderId: "code",
appId: "code",
measurementId: "code"
};
const firebaseApp = initializeApp(firebaseConfig);
export default firebaseApp
My component file using firebaseConfig.js in ./src/components/HellowWorld.vue :
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<div id="sign-in-status"></div>
<div id="sign-in"></div>
<pre id="account-details"></pre>
</div>
</template>
<script>
import firebaseConfig from '../firebaseConfig';
import firebase from 'firebase/compat/app';
import * as firebaseui from 'firebaseui'
import 'firebaseui/dist/firebaseui.css'
console.log(firebaseConfig);
console.log(firebase);
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
ui
export default {
name: 'HelloWorld',
props: {
msg: String
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
both
console.log(firebaseConfig);
console.log(firebase);
works but
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
ui
produces an error as copy and pasted above.
I had same problem, then I found points. And I understood why somebody was OK, others was bug.
Initialization needs to App based, of course before call firebaseUI. We have some ways to do that
main.js, import configuration.js, before auth timing...etc.
Initialized firebaseApp (your firebaseConfig.js) is different from import firebase from 'firebase/compat/app'
If new firebaseUI is called before Initialization or no initialized, we get error. Then take care Lifecycle of Vue.
Probably you need,
Import firebaseApp, Not firebaseConfig to HellowWorld.vue for getting Initialized.
In my case, my 'new firebaseUI' is in mounted() of ChildView. I initialize firebaseApp at main.ts, so childView doesn't need initialization any more, only import firebase from 'firebase/compat/app'.
If you need code, I can show you my case.

Where is 'initializeApp' in firebase imports?

So I started taking a look into firebase and just after defining the intialization as
import firebase from "firebase/compat"
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID,
measurementId: process.env.REACT_APP_MEASUREMENT_ID
};
const chatSupportApp = firebase.initializeApp(firebaseConfig, "my-app");
A wild warning was display!
/*It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');
ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
Typescript:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';*/
I search in many posts, including documentation and didn't really get how to initialize my app first before using any of the other imports
I found out lately that is was a bit hidden under "firebase/firebase-app"
so it get solved, as
import {initializeApp} from "firebase/firebase-app";
const firebaseConfig = {
apiKey: ...............
};
const chatSupportApp = initializeApp(firebaseConfig, "my-app");
export default chatSupportApp;
This started as a question that I search in most stack overflow posts, but since I solve it for now somehow I wanted also to share with the community in here, but also consider any other suggestion, the question will be then.
Is this approach correct? why all the documentation suggest to do it with
import { initializeApp } from 'firebase/app'; as:
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged, getRedirectResult } from 'firebase/auth';
This really didn't work for me at all and I was not able to use it.
Thanks and enjoy your code!
import {initializeApp} from "firebase/firebase-app";
const firebaseConfig = {
apiKey: ...............
};
const chatSupportApp = initializeApp(firebaseConfig, "my-app");
export default chatSupportApp;

FCM React.js/Node npm: TypeError: Cannot assign to read only property 'toJSON' of object 'Error'

I am trying to get FCM working on our company's client React.js web app and after reviewing the Firecasts on the subject and finding and following this Medium tutorial on using firebase cloud messaging with React.js, it keeps erroring on app boot. If I comment out the initialization for Firebase, the app boots without issue.
I used node npm to install the firebase module and created the required push-notification.js and firebase-messaging-sw.js files outlined in the tutorial. I have tried narrowing down the config var to just the messagingSenderId and that did resolve the error. I am not sure what else to try as this is my first time working with Firebase and am quite new to their libraries and SDK's.
Below I will give as much code context as possible. For liability reasons, I cannot display out all the context code but will try to produce the relevant snippets and import statements. In addition, all keys, passwords, or other identifiers that are sensitive will be removed as well.
index.js file code:
import { initializeFirebase, askForPermissionToReceiveNotifications } from './push-notification';
ReactDOM.render(<ReduxApp />, document.getElementById('root'));
initializeFirebase();
askForPermissionToReceiveNotifications();
push-notification.js file code:
import firebase from 'firebase';
export const initializeFirebase = () => {
var config = {
apiKey: "apiKey",
authDomain: "authDomain",
databaseURL: "databaseURL",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId"
};
firebase.initializeApp(config);
}
export const askForPermissionToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('user token:', token);
return token;
} catch (error) {
console.error(error);
}
}
messaging.onMessage(function(payload) {
console.log('onMessage: ', payload);
})
firebase-messaging-sw.js file code:
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
firebase.initializeApp({
apiKey: "apiKey",
authDomain: "authDomain",
databaseURL: "databaseURL",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId"
});
const messaging = firebase.messaging();
On app boot and with the import firebase from 'firebase'; statement active (not commented out), I get: TypeError: Cannot assign to read-only property 'toJSON' of object 'Error'
When I comment out the import firebase from 'firebase'; statement and the function calls in index.js, the app boots with no errors.
If you need more context to assist with this problem, let me know what you need/want to see and I will add it in.
It looks like that was done on purpose because it prevents authentication upon error. I would guess that it's your actual token value, not variable, that's wrong. Good luck :)
I found that the TypeError went away when I used this type of import:
import firebase from 'firebase/app';
import 'firebase/messaging';
There are still other bugs in this solution. But the light at the end of the tunnel is now visible.

Categories