Hello I am trying to configure react app with firebase and use firestore.
"firebase": "^9.1.3"
I followed the instructions given in official docs.
Here is my congig.js file.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: '****',
authDomain: '*****',
projectId: '*****',
storageBucket: '*****',
messagingSenderId: '****',
appId: '*****',
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
I am sure this gets initialized.
When I export it and use it in other file. collection is greyed out in vs code that means i am not using the import.
databaseservice.js
import { db } from './config';
import { collection, doc } from 'firebase/firestore';
export const getChapters = (scanId) => {
db.collection('somecollection')
.doc(scanId)
.get()
.then((doc) => {
if (doc.exists) {
console.log('Document data:', doc.data());
} else {
// doc.data() will be undefined in this case
console.log('No such document!');
}
})
.catch((error) => {
console.log('Error getting document:', error);
});
};
Error:TypeError: config__WEBPACK_IMPORTED_MODULE_0_.db.collection is not a function
I have tried with compat and lite versions. Getting the same issue.
This is v8/compat syntax:
db.collection('somecollection')
.doc(scanId)
.get()
.then((doc) => {
In v9/modular syntax, the equivalent is:
getDoc(doc(db, 'somecollection', scanId))
.then((doc) => {
For converting this type of thing, I find it easiest to keep the Firebase documentation and upgrade guide handy.
Firebase have changed their API to new modular syntax in version 9. You are using old syntax from version 8. You can read more about this and find instructions on upgrading your code here: https://firebase.google.com/docs/web/modular-upgrade
Also, everywhere in Firebase documentation, they now have 2 separate examples: one for old syntax, one or new modular syntax: https://firebase.google.com/docs/firestore/query-data/get-data
Related
I have config/firebase.ts:
import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore'
const firebaseAdminApp = initializeApp({
credential: cert({
privateKey: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
clientEmail: process.env.NEXT_PUBLIC_FIREBASE_SERVICE_EMAIL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}),
databaseURL: `https://${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseio.com`
});
const firestore = getFirestore(firebaseAdminApp);
export default firestore
and when trying to upsert, I have:
import firestore from "../config/firebaseAdmin";
const upsertInstance = async (instance: Instance) => {
const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
const res = await firestore.doc(`instances/${hashedUri}`).set(instance);
return res
}
but I get:
Error: expected a function
What am I doing wrong?
Firebase Admin is not totally modular yet like the client SDK yet so you would have to use namespaced syntax. Admin SDK's Firestore instance won't work perfectly with client SDK functions. Try refactoring the code as shown below:
export const db = getFirestore(firebaseAdminApp);
import { db } from "../path/to/firebase"
const upsertInstance = async (instance: Instance) => {
const res = await db.doc(`instances/${instance.uri}`).set(instance);
return res;
}
Checkout the documentation for more information.
I made a Firebase app with database, connected it with Vue app, which is like todo-list. I tried to get a data from database from firebase, which is used to make components for app, but something got wrong. Vue app doesn't get the data from firebase, so items aren't created
It's th error:
#firebase/firestore: Firestore (9.10.0): Uncaught Error in snapshot listener: {"code":"permission-denied","name":"FirebaseError"
Initializing firebase:
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import { getFirestore } from "#firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyBZlP_E74i40ZLopttFlUbg3j36wirKf9A",
authDomain: "quotes-app-8788c.firebaseapp.com",
projectId: "quotes-app-8788c",
storageBucket: "quotes-app-8788c.appspot.com",
messagingSenderId: "934346412075",
appId: "1:934346412075:web:5da2928fecb05c834f5a6e"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export {
db
}
Here is my code:
onSnapshot(collection(db, 'quotes'), (QuerySnapshot) => {
const fbquotes = [];
QuerySnapshot.forEach((doc) => {
const quote = {
id: doc.data().id,
quoteText: doc.data().quoteText,
quoteAuthor: doc.data().quoteAuthor,
quoteGenre: doc.data().quoteGenre,
timeCreating: doc.data().timeCreating,
timeEditing: doc.data().timeEditing
}
this.fbquotes.push(quote)
})
this.quotes = fbquotes
console.log(this.quotes);
})
console.log(this.quotes);
},
The error code "permission-denied" tells that your security rules are not allowing the user to query that whole collection. If a user can read all documents from the "quotes" collection then make sure you have the following rules:
match /quotes/{quotesId} {
allow read: if true;
}
You can change the condition for allow read if your requirements are different. Also Security Rules are not filters so if you want to allow a user to read their own documents only, then make sure you change the query in your code as well to match the security rules.
I am pretty new to expo and firebase, and I have this error that I have no idea what the issue is. I am trying to fetch photos from firebase database. I know for sure the issue is not with firebase config because I can upload photos into firebase storage.
I suspect the issue is with exporting and importing firebase.
This is the error message I am getting :
[TypeError: _firebase.db.ref is not a function. (In
'_firebase.db.ref('users/photos')', '_firebase.db.ref' is undefined)]
Note: I am using firebase v9
App.js file:
import { db } from './firebase';
export default function App() {
async function loadPhotos() {
try {
db.ref('users/photos')
.then(url => {
console.log('URL: ', url);
})
.catch(e => console.log(e));
console.log('Got here');
} catch (error) {
console.log('error', error);
}
}
...............
}
firebase.js file:
import firebase from 'firebase/compat/app';
import { getDatabase } from 'firebase/database';
const firebaseConfig = {
apiKey: '......',
authDomain: '.....',
projectId: '....',
storageBucket: '....',
messagingSenderId: '....',
appId: '.....',
measurementId: '....',
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export const db = getDatabase();
In v9 and later of the Firebase SDK, most functionality that was a method on the objects in the past, is now available as a top-level function.
So instead of db.ref('users/photos'), you need to do ref(db, 'users/photos').
You're also missing a get call, which is how you actually retrieve the data from the reference:
get(ref(db, 'users/photos'))
.then(url => {
console.log('URL: ', url);
})
.catch(e => console.log(e));
This is all pretty well documented in the Firebase documentation on reading data, so I recommend keeping that handy. Alternatively you can use the compat paths in v9, to make the older syntax work as shown in the upgrade guide/
I'm trying to implement Vuefire in my project. I'm following the guidelines on the Vuefire site but still get this error.
db.js:
import firebase from 'firebase/app'
import 'firebase/firestore';
const firebaseConfig = {
apiKey: ....,
authDomain: ....,
projectId: ....,
storageBucket: ...,
messagingSenderId:....,
appId: ..."
};
const app = firebase.initializeApp(firebaseConfig)
export const db = app.firestore()
main.js
import Vue from 'vue';
import App from './App.vue';
import vuetify from './plugins/vuetify';
import { firestorePlugin } from 'vuefire'
import DatetimePicker from 'vuetify-datetime-picker';
Vue.use(firestorePlugin)
Vue.config.productionTip = false;
Vue.use(DatetimePicker)
new Vue({
vuetify,
render: h => h(App)
}).$mount('#app');
App.vue
import { db } from "../db";
export default {
name: "App",
data() {
return {
fireDB: [],
},
mounted() {
console.log(this.fireDB);
},
firestore: {
// fireDB: db.collection("something").doc('else').get().then((res) => {
// console.log(res);
// }) - like this it gives me the error.
//fireDB: db.collection("something") - like this it returns an array with an object that is my database.
},
};
from the console I see that the 'document' upon which onSnapshot is called is a promise
I'm not sure if this is the cause of your problem, but I got the same error when using VuexFire and it was because I had installed the Firebase v9 which has a new API and isn't compatible with Vuefire yet.
You can either try to use the new Firebase v9 API or downgrade to v8 - which is what the example code in the current Viewfire site uses (actually I think it says it's v7 but it works with v8).
To downgrade, check your package.json for the version of Firebase, and ensure it's v8 e.g. "firebase": "^8.10", (and run npm i)
This is the v8 query syntax
https://firebase.google.com/docs/firestore/quickstart#web-version-8_4
db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
});
This is the v9 syntax
https://firebase.google.com/docs/firestore/quickstart#web-version-9_4
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
I found that VuexFire v3.2.5 worked when POSTing new documents to Firebase v9, but I got the onSnapshot error when binding a collection. So I downgraded to Firebase v8 and switched my bindings to the old syntax (as per the Viewfire docs).
There is an Viewfire issue about upgrading which is active (as of Oct 2021) but not complete yet. https://github.com/vuejs/vuefire/issues/1128
I want to reload or trigger some event in foregrounf if push message is sent with firebase.messaging().onMessage, but it not fired. I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?
firebase.js
const config = {
apiKey: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x"
};
firebase.initializeApp(config);
const msg = firebase.messaging()
msg.requestPermission()
.then(() => {
return msg.getToken()
})
.then((token) => {
})
.catch((err) => {
})
msg.onMessage(function(payload) {
alert("Foreground message fired!")
console.log(payload)
});
firebase.messaging.sw.js
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-messaging.js");
const config = {
apiKey: "x",
projectId: "x",
storageBucket: 'x',
messagingSenderId: "x"
};
firebase.initializeApp(config);
const msg = firebase.messaging()
msg.setBackgroundMessageHandler(function(payload) {
let options = {
body: payload.data.body,
icon: payload.data.icon
}
return self.registration.showNotification(payload.data.title, options);
});
I don't know what is wrong with my code
Simple solution to this is update your Firebse to latest version.
Eg.
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
Note: Once you have updated your firebase libraries versions then messagingSenderId will not work in your firebase-messaging-sw.js file. You have to provide all other params eg. apiKey, projectId, appId along with messagingSenderId.
If still not work. Clean your browser cache and re-register service worker.
For more details you can refer to this solution
Still had the same issue in 2020. In my case it was like this:
you need to have same versions in importScripts for background messages and in your app for foreground messages
call it after obtaining token for background service
firebaseApp.messaging().getToken().then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
// Show permission request.
console.log(
'No Instance ID token available. Request permission to generate one.')
}
/** When app is active */
firebase.messaging().onMessage((payload) => {
console.log(payload)
}, e => {
console.log(e)
})
})
For anyone else with this problem, I finally solved it by:
Upgrading the Firebase SDK version in both header-included JS files and the SW JS file to latest (currently, that would be 7.8.1).
Adding the entire firebaseConfig array to the SW firebase.initializeApp(), as the previous answer suggests.
Cleaning the Chrome cache from the Application > Clear Storage section in the Developer Tools.
Deleting the previous registration token from my database.
Blocking and unblocking notifications from the browser to force a new token generation.
Basically, a total fresh start with updated Firebase SDK seems to fix issues like this.
You are missing lots of things and onMessage will only work if firebase is initialized before calling it. Please follow this. I have done it like this and it is working.
initialize firebase and get the token
export class BrowserFcmProvider {
export const FIREBASE_CONFIG = {
apiKey: "****",
authDomain: "****",
databaseURL: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****"
}
firebase.initializeApp(FIREBASE_CONFIG);
async webGetToken() {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
let uuidTemp = new DeviceUUID().get();
return this.saveTokenToFireStoreFromWeb(token, uuidTemp)
} catch (e) {
console.log(e);
}
}
saveTokenToFireStoreFromWeb(token, uuid) {
try {
const docData = {
token: token,
device_type: 'web',
uuid: uuid
}
const devicesRef = this.db.collection('devices')
return devicesRef.doc(uuid).set(docData);
} catch (e) {
console.log(e, 'saveTokenError');
}
}
showMessage() {
try {
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log(payload);
})
} catch (e) {
console.log(e)
}
}
}
And calling the method while app loads like this
async configureFirebaseForBrowser(res) {
await this.bfcm.webGetToken();
this.bfcm.showMessage();
}
Firebase function and payload type
const payloadWeb = {
title: title,
body: body,
data: {
title: title,
body: body
},
tokens: uniqueDevicesTokenArrayWeb,
}
const responseWeb = await admin.messaging().sendMulticast(payloadWeb);
console.log(responseWeb.successCount + ' notifications has been sent to Web successfully');
I have used async and await as we need to manage firebase/firestore operations asynchronously.
fcm does not work in Incognito mode and safari browser
Same issue i was faced. In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different. After set same version in "firebase-messaging-sw.js" importScripts which was in
"package.json", my issue is resolved.
Before change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
After change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');