Getting firebase is not defined on setting document in html/ javascript - javascript

So, basically i am trying to save data in firebase an am getting the error "firebase is not defined"
my code:-
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
firebase // getting error over here
.firestore()
.collection("books")
.add({
title: "Of Mice and Men",
})
.then((ref) => {
console.log("Added doc with ID: ", ref.id);
// Added doc with ID: ZzhIgLqELaoE3eSsOazu
});

Since version 9 of its JavaScript SDK, Firebase has switched to a new modular syntax where you import individual functions. You'll have to choose whether you want to use the new syntax, or continue using the previous syntax through its compatibility layer.
To import the compatibility libraries, use:
// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
To then switch to the new syntax, follow the instructions in the same upgrade guide, and in the v9 tab of the code samples in the rest of the documentation.

Related

Service Firestore not available Nuxt2 Firebase

While deploying the SSR Nuxt 2 to firebase with functions and hosting it throws the following error in the image
Firebase.js code
// import { initializeApp } from "firebase/app";
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
require("firebase/compat/firestore");
var firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
var fb = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export { fb,db };
As Mentioned by #kissu, the issue seems to be with the firebase version.
Try upgrading to the latest firebase version. Since lower versions of Firebase doesn't have the updated compat libraries.
And Sometimes Package managers have some issues while updating the libraries to the latest version. You can resolve these issues by reinstalling firebase or deleting and adding node_modules and package.json.
Also check this similar thread

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.

React Native - TypeError: _firebase.default.auth is not a function

I have a React Native App and have the following function:
import firebase from './firebase'
export function MainNavigator() {
const [token, setToken] = useAtom(tokenAtom);
useEffect(() => {
firebase.auth().onIdTokenChanged(async (user) => {
setToken(user ? await user.getIdToken() : null);
});
}, []);
.....
.... more code
This above code worked in Expo, but I have a new react native project (not built using expo) and this is failing:
I have the following in my package.json file:
"#react-native-firebase/app": "^13.0.1",
"#react-native-firebase/functions": "^13.0.1",
"firebase": "^9.5.0",
And my firebase.js file is like so (root directory)
import * as firebase from "firebase/app";
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "Secret stuff",
authDomain: "Secret stuff",
databaseURL: "Secret stuff",
projectId: "Secret stuff",
storageBucket: "Secret stuff",
messagingSenderId: "Secret stuff",
appId: "Secret stuff",
measurementId: "Secret stuff"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase;
Im getting the following error:
TypeError: _firebase.default.auth is not a function. (In
'_firebase.default.auth()', '_firebase.default.auth' is undefined)
None of the code you show imports the Firebase Authentication SDK. So when you then try to use firebase.auth() it correctly indicates that it can't find that SDK.
I'm guessing you want to import the Auth SDK too with something like:
import "firebase/auth";
I'd also recommend checking out the documentation on upgrading to the v9 or v9/compat SDK.
// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
docs

React Native firebase is undefined

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

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