Data is not captured in firestore react native - javascript

I'm using firestore with react native like below, but while running my app data is not added to the cloud. am not sure why, please help me to understand the actual problem here.
componentWillMount() {
console.log('Test1');
firebase.initializeApp({
apiKey: 'xxxxxxx',
authDomain: 'testing-8ex763xxxxxxxxxxxxxx',
databaseURL: 'https://testing-8e76xxxo.com',
projectId: 'testing-xxxxx',
storageBucket: 'testing-8xxxxx.com',
messagingSenderId: '73664xxx042'
});
firebase.firestore().enablePersistence()
.then(function() {
// Initialize Cloud Firestore through firebase
var db = firebase.firestore();
console.log('Test3', db);
db.collection('us').add({
first: 'hai',
last: '111',
born: 1815
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
})
.catch(function(err) {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
// ...
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
}

You have not given the reference of doc.
And also use 'set' instead of add method.
db.collection('us').doc('some_name').set({
first: 'hai',
last: '111',
born: 1815
})

Related

How to connect to Firebase Firestore?

I want to get data from a Firestore Database, however, instead of getting an Array of 1 element, I get [Al] which I'm not sure what it is.
This is the code I have in my Index.html. I have changed the information inside the config object for security reasons here.
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "my api key",
authDomain: "demo",
databaseURL: "my url",
projectId: "my project",
storageBucket: "bucket",
messagingSenderId: "1051539927876",
appId: "my app id",
measurementId: "0000000000"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
firebase.analytics();
</script>
<script src="app.js"></script>
And this is what I have inside my app.js file
db.collection('cafes').get().then((snapshot) => {
console.log(snapshot.docs);
}).catch(err => {
console.log(err);
});
You need to do the following to get the data:
db.collection('cafes').get().then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
}).catch(err => {
console.log(err);
});
doc.data() will contain the data of the documents.
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
var docRef = db.collection("cafes").doc("cafe_name");
docRef.get().then(function(doc) {
console.log("document data:", doc.data());
}).catch(function(error) {
console.log("Error getting data:", error);
});
or
db.collection("cafes").doc("cafe_name").get().then(function(doc) {
console.log("document data:", doc.data());
}).catch(function(error) {
console.log("Error getting data:", error);
});
You need to change "cafe_name" to the name of an item of cafes.

Node.js Firestore authentication issues (while javascript works)

I am looking to anonymously connect to a Firestore and grab some data from a collection. This works perfectly fine under javascript, while it fails ("FirebaseError: Missing or insufficient permissions") under node.js. Any pointers will be appreciated.
This is the code that works without a hitch under javascript (I have omited the 'script' includes) and it returns data as expected:
var config = {
apiKey: "xxx",
authDomain: "xxx.firebaseio.com",
projectId: "xxx",
storageBucket: "xxx.appspot.com",
};
firebase.initializeApp(config);
firebase.auth().signInAnonymously().catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(error.message);
});
foo();
async function foo() {
var db=firebase.firestore();
var query = await db.collection("collection").limit(5).get();
query.forEach(function(doc) {
console.log(doc.data());
});
}
This is the code that does not work under node.js. The config/authdata is exactly the same as in the js example above. (It uses the firebase (client) library. My understanding is that the firebase-admin library does not allow anonymous signin.)
const firebase=require('firebase');
var config = {
apiKey: "xxx",
authDomain: "xxx.firebaseio.com",
projectId: "xxx",
storageBucket: "xxx.appspot.com",
};
firebase.initializeApp(config);
firebase.auth().signInAnonymously().catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(error.message);
});
let db = firebase.firestore();
db.collection('collection').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
})
.catch((err) => {
console.log('Error getting documents', err);
});
The following error is triggered when db.collection('collection').get() is called. (earlier anonymous signing goes through)
Error getting documents { FirebaseError: Missing or insufficient permissions.
at new FirestoreError (/root/node_modules/#firebase/firestore/dist/index.node.cjs.js:1201:28)
at JsonProtoSerializer.fromRpcStatus (/root/node_modules/#firebase/firestore/dist/index.node.cjs.js:19708:16)
at JsonProtoSerializer.fromWatchChange (/root/node_modules/#firebase/firestore/dist/index.node.cjs.js:19955:44)
at PersistentListenStream.onMessage (/root/node_modules/#firebase/firestore/dist/index.node.cjs.js:16828:43)
at /root/node_modules/#firebase/firestore/dist/index.node.cjs.js:16757:30
at /root/node_modules/#firebase/firestore/dist/index.node.cjs.js:16797:28
at /root/node_modules/#firebase/firestore/dist/index.node.cjs.js:17844:20
at process._tickCallback (internal/process/next_tick.js:68:7)
code: 'permission-denied',
name: 'FirebaseError',
toString: [Function] }
Thanks again for any pointers!
One possibility is that you are actually not signed-in when you fetch Firestore. As a matter of fact the signInAnonymously() method is asynchronous and you don't wait that the Promise returned by this method resolves before fetching Firestore.
So, the following may solve your problem:
firebase.initializeApp(config);
let db = firebase.firestore();
firebase.auth().signInAnonymously()
.then(cred => {
return db.collection('collection').get()
})
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
})
.catch((err) => {
console.log(err);
});
Note that you should do the same in the JavaScript SDK version:
firebase.auth().signInAnonymously()
.then(cred => {
foo();
}}
.catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(error.message);
});

FCM This site has been updated in the background

So I'm using VueJS with the PWA option enabled. When using Firebase Cloud Messaging (for web app), I'm getting a notification saying: This site has been updated in the background but Only when the tab is not focused or open. If the tab is active, I don't receive anything in the console.
I'm using Postman to send notifications for now, and it returns success
{
"multicast_id": 5364665067527599460,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1550148053476716%2fd9afcdf9fd7ecd"
}
]
}
Here is my main.js
const config = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("PUBLIC_VAPID_KEY");
navigator.serviceWorker.register('./firebase-messaging-sw.js')
.then((registration) => {
console.log("Now using registration: " + registration);
messaging.useServiceWorker(registration);
}).catch(err => {
console.log("Error in registration");
console.log(err)
});
My firebase-messaging-sw.js (I never saw the console log thats inside setBackgroundMessageHandler)
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-messaging.js');
var config = {
messagingSenderId: 'SENDER_ID'
};
firebase.initializeApp(config);
let messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
return self.registration.showNotification('title', {body: 'message'});
});
And in my App.vue (neither have I ever seen the console log in onMessage)
created() {
this.$messaging.onMessage(function(payload) {
console.log('Message received: ', payload);
// ...
});
},
methods: {
sendNotif() {
this.$messaging.requestPermission().then(() => this.$messaging.getToken())
.then((token) => {
console.log(token) // Receiver Token to use in the notification
})
.catch(function(err) {
console.log("Unable to get permission to notify.", err);
});
},
},
I can access the token, none of my configuration is wrong or else the postman request wouldn't give success. I've checked out several other questions related to this but no success so far...

FCM.getToken() promise never resolved

I'm trying to implement web push notifications with FireBase. It works good in desktop chrome/firefox, but when it comes to android I can't get the notification token - the promise, returned from messaging.getToken is never resolved, neither throws an error (always pending). I have a service worker, and it is active and running. Here is my code - what do I do wrong?
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase-messaging.js"></script>
<script>
var config = {
apiKey: "AIzaSyBuFGsjFDCILwYVzLHWLvoRIHSoDZIQBl8",
authDomain: "mobilepush-fd2d5.firebaseapp.com",
databaseURL: "https://mobilepush-fd2d5.firebaseio.com",
projectId: "mobilepush-fd2d5",
storageBucket: "mobilepush-fd2d5.appspot.com",
messagingSenderId: "106871298920"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("BBYGyuGH2KqQSHyc55Di5IQnHc52fY6gqmExfWtg85-wabmQimja6X6ViR2jmNgPBZBuLeX0BXf9A0yLqUV5m90");
var curStatus = messaging.getNotificationPermission_();
if (curStatus == 'granted') {
messaging.getToken().then(function(currentToken) {
if (currentToken) {
processToken(currentToken, 1);
} else {
reqPerm();
}
}).catch(function(err) {
//error
});
} else if (curStatus == 'denied') {
//denied
} else {
reqPerm();
}
function reqPerm() {
messaging.requestPermission().then(function() {
messaging.getToken().then(processToken);
}).catch(function(err) {
//error
});
}
function processToken(token, hasAlready) {
alert(token);
}
</script>
Found it - the phone memory was absolutely full, so Firebase script couldn't add token data to the local indexeddb of the browser. Deleted some files on device and now it works.

Does not delete document from firebase when click on button (onclick method)

Does not delete stored document in cloud-firestore.
When i run my program 5 buttons are show (because my firestore documents are 5) and when i click button then show error test.html:1 Uncaught ReferenceError: ds5678fhiksnie is not defined
at HTMLButtonElement.onclick (test.html:1)
I want to
when button is clicked then id according document is deleted.
<html>
<body>
<!-- parent named class inner buttons according document stored in cloud-firestore-->
<div class="parent"></div>
<-- api -->
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script
src="https://www.gstatic.com/firebasejs/4.9.0/firebase-firestore.js"></script>
<script>
// web setup this is sample
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
firebase.initializeApp(config);
</script>
<script>
var db = firebase.firestore();
// inserting one record automatic id
db.collection("users").add({
first: "Ada",
last: "Lovelace",
born: 2000
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
// get element
var p =document.querySelector(".parent");
// display the document
db.collection("users").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var d=String(doc.id);
console.log(d);
// if stored documents are 5 then 5 buttons will display
p.innerHTML+="<button onclick=delet("+String(d)+")>Hello</button>";
});
});
// delete function(id passing)
function delet(v) {
console.log(v);
db.collection("users").doc(v).delete().then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
}
</script>
</body>
</html>
Using JavaScript literals
<html>
<head>
</head>
<body>
<div class="parent">
</div>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-firestore.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: ####,
authDomain: ####,
databaseURL: ####,
projectId: ###,
storageBucket: ###,
messagingSenderId: ###
};
firebase.initializeApp(config);
</script>
<script>
var db = firebase.firestore();
db.collection("users").add({
first: "Ada",
last: "Lovelace",
born: 2000
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
var p = document.querySelector(".parent");
db.collection("users").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var d=String(doc.id);
console.log(d);
p.innerHTML+=`<button onclick="deleti('${d}')">Ok</button>`;
});
});
function deleti(v) {
v=v.toString();
console.log(v);
db.collection("users").doc(v).delete().then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
}
</script>
</body>
</html>
try collection.child(v).remove() then handler your callbacks.

Categories

Resources