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;
};
Related
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>
I'm getting the error:
Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but todos has 1.
I wrote code because I want to inquire the data in the DB.
No matter how much I searched, I couldn't find the answer. which part is wrong
this is my firebaseConfig code:
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/auth";
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***",
};
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
export const auth = firebase.auth();
export const apiKey = firebaseConfig.apiKey;
this is code of firebaseController.tsx:
export const todos = firestore.collection('todos');
and this is code of view component:
useEffect(() => {
onSnapshot(todos, (snapshot: QuerySnapshot<DocumentData>) => {
setTodoItems(
snapshot.docs &&
snapshot.docs.map((doc) => {
return {
id: doc.id,
...doc.data(),
};
})
);
});
}, []);
my database:
DB
The onSnapshot method works on Firebase Documents, not on Firebase Collections. The first argument to onSnapshot you give i.e. "todos" is a collection reference but in reality, it expects a document reference, which you obtain by using the method
const docRef = doc(db, "path/to/document/inside/todos/collection")
onSnapshot(docRef, ......)
Hope this helps!
I'm using my API key stored in a .env.local file. And it setup correctly but not working
assert.ts:128 Uncaught FirebaseError: Firebase: Error (auth/invalid-api-key).
at createErrorInternal (assert.ts:128:1)
at _assert (assert.ts:153:1)
at register.ts:67:1
at Component.instanceFactory (register.ts:90:1)
at Provider.getOrInitializeService (provider.ts:318:1)
at Provider.initialize (provider.ts:242:1)
at initializeAuth (initialize.ts:66:1)
at getAuth (index.ts:44:1)
at Module../src/firebase.init.js (firebase.init.js:22:1)
at Module.options.factory (react refresh:6:1)
I don't know why React is giving me an error. I intialized firebase in the following file
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
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,
measurementId:process.env.REACT_APP_measurementId
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export default auth;
It is likely that you are having multiple render of your app. Do it this way:
const firebaseConfig = {
apiKey: process.env.REACT_APP_apiKey || 'test',
authDomain: process.env.REACT_APP_authDomain || 'test',
projectId: process.env.REACT_APP_projectId || 'test',
storageBucket: process.env.REACT_APP_storageBucket || 'test',
messagingSenderId: process.env.REACT_APP_messagingSenderId || 'test',
appId: process.env.REACT_APP_appId || 'test',
measurementId:process.env.REACT_APP_measurementId || 'test'
};
In that case at the first render, when the environment variables are yet available, you will have default values, not null or undefined values.
I hope it helps someone.
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.
I want to create FCM token for web application based on this i want to send push notifications.Is it possible?Can i expect sample code for this?
I try this one
var config = {
apiKey: "AIzaSyC2GoeeoYfPTgP61w77FMPFep-cLBz9Pmc",
authDomain: "sample-3a7a1.firebaseapp.com",
databaseURL: "https://sample-3a7a1.firebaseio.com",
projectId: "sample-3a7a1",
storageBucket: "sample-3a7a1.appspot.com",
messagingSenderId: "990467369229"
};
firebase.initializeApp(config);
const messaging=firebase.messaging();
messaging.requestPermission()
.then(function(){
console.log('Have permission');
return messaging.getToken();
})
.then(function(token){
console.log(token);
})
but it shows following error
Uncaught e {code: "app/no-app", message: "Firebase: No Firebase App '[DEFAULT]' has been cre…- call Firebase App.initializeApp() (app/no-app).", name: "[DEFAULT]", stack: "FirebaseError: Firebase: No Firebase App '[DEFAULT… at http://localhost:8080/FCMPushNotify/:88:30"}