FCM - firebase App not initialised - React Native - javascript

I am configuring and initialising firebase app still FCM messaging results in an error saying Firebase App not initialised.
import FCM from "react-native-fcm";
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xxx",
messagingSenderId: "xxx",
storageBucket: "xxx",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
class App extends Component {
configureStore()
{
const store = createStore(reducer,undefined,compose(autoRehydrate()));
persistStore(store,{ storage: AsyncStorage })
return store;
}
constructor(props)
{
super(props);
}
componentDidMount()
{
FCM.requestPermissions()
.then(()=>console.log('granted'))
.catch(()=>console.log('notification permission rejected'));
FCM.getFCMToken()
.then(token => {
alert("TOKEN (getFCMToken)", token);
})
.catch((error)=> alert(error))
}
}
FCM notification permission is granted but then the getToken method results in an error of firebase app not initialised instead of initialising it at the top,

You have to call FCM.getFCMToken() inside FCM.requestPermissions().then() because requestPermissions is async

According to "react-native-fcm",
react-native-firebase now can do what react-native-fcm can so it is a
waste of effort to build the same thing in parallel.
As compare to reac-native-fcm you have to use react-native-firebase.
Here you can find the docs and its easy to use and integrate in react-native.

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>

Error get FCM token on firebase version 9

yesterday my application had no problems when it wanted to request fcm tokens, suddenly now it can't, and the error that appears is:
error result
my assumption is because firebase-messaging-sw can't be active, it's not even in the build result folder, even though yesterday there was no problem at all. the firebase I'm using is version 9 so it's modular.
firebase-messaging-sw.js
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
apiKey: "--------",
authDomain: "-------",
projectId: "------",
storageBucket: "-----",
messagingSenderId: "------",
appId: "---------"
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);
main.js
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import { initializeApp } from "firebase/app";
import './utils/firebase-messaging-sw'
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: "---------------------",
authDomain: "-----------------------",
projectId: "---------------------",
storageBucket: "----------------------",
messagingSenderId: "-----------------------",
appId: "---------------------------"
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging();
getToken(messaging, { vapidKey: '---------------------------------' }).then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
createApp(App).use(store).use(router).mount('#app')
after build the firebase-messaging-sw.js file should also be in it, that's what happened yesterday, but somehow now suddenly it can't
build result
because i use pwa, there should be 2 active service workers
service worker from Vue
service worker from firebase-messaging-sw
in fact the only active ones are vue's service workers
active service workers
here is my directory structure
directory

Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]

I am getting the following error: Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]: Permission denied on resource project disneyplus-clone-a33d5.
I am learning React and the tutorial I am learning from uses firebase. I have very little knowledge about firebase. I cannot find any solution for this error. here is my fbconfig.js :
import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider } from "firebase/auth";
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore"
const firebaseConfig = {
apiKey: "---",
authDomain: "--.firebaseapp.com",
projectId: "--",
storageBucket: "--",
messagingSenderId: "--",
appId: "--",
measurementId: "---",
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth();
const provider = new GoogleAuthProvider();
const storage = getStorage(firebaseApp);
export { auth, provider, storage };
export default db;
Here is my Home.js :
import db from '../fbconfig'
import { doc, onSnapshot, collection, query, where } from "firebase/firestore";
function Home() {
useEffect(() => {
const q = query(collection(db, "movies"))
const unsub = onSnapshot(q, (snapshot)=>{
let tempMovies = snapshot.docs.map((doc)=>{
console.log(doc.data());
return { id: doc.id, ...doc.data() }
})
});
code=permission-denied when working with Firestore is always a permissions problem on the collection you are trying to read, in this case "movies". To set permissions on a collection you can use the Firebase web gui or the command line tools.
The specific rule you will need for read access to "movies" is
match /movies {
allow get: if true;
allow list: if true;
allow update: if false;
allow create: if false;
allow delete: if false;
}
https://firebase.google.com/docs/rules/manage-deploy
Or the web ui

Firebase - Failed to get document because the client is offline (v9 Upgrade)

Recently upgraded to firebase v9 from v8 in my React Native project and I am now unable to use my legacy v8 firestore methods.
The error I am receiving is:
[Unhandled promise rejection: FirebaseError: Failed to get document because the
client is offline.]
I initialize firebase in a file I call fire-config.js. The commented //import firebase from 'firebase'; is how I previously imported firebase in v8.
I then would import fire from fire-config.js into my controller methods. Ex: userController.js.
I tried a couple different combinations of /compat and /compat/app to no avail. I was following the upgrade guide (https://firebase.google.com/docs/web/modular-upgrade) which my understanding was update the path and that was all that was needed.
Package.json:
"firebase": "9.0.2",
fire-config.js
//import firebase from 'firebase';
import firebase from 'firebase/compat';
require("firebase/functions");
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXX",
projectId: "XXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXXX",
appId: "XXXX",
measurementId: "XXXXX"
};
try {
firebase.initializeApp(firebaseConfig);
} catch(err){
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)}
}
const fire = firebase;
export {fire};
userController.js
import {fire} from "../config/fire-config";
const getUserDetail = async (user) => {
let userDetail = {};
await fire
.firestore()
.collection("users")
.doc(user.uid)
.get()
.then((doc) => {
if (doc.exists) {
userDetail = {
id: doc.id,
...doc.data(),
};
}
});
return userDetail;
};

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