firebase emulator data not saved and retrieved from some cache - firebase

Getting data from firestore emulator works fine, manually added documents.
export const getMaterials = async (companyID: string): Promise<Material[]> => {
const materials = await getDocs(collection(db,
`${COMPANIES}/${companyID}/materials`))
return materials.docs.map<Material>((doc) => <Material>{ id: doc.id, ...doc.data() })
}
Saving also return with success but the data is not shown in the emulator UI but return from the above function the records from the emulator and the newly added records.
The data disappear after refreshing the app and the emulator.
export const setMaterial = async (
companyID: string,
id: string
): Promise<any> => {
const docData = {
companyID: companyID,
id: id,
name: name
}
const ret = await addDoc(collection(db, `${COMPANIES}/${companyID}/materials`),
docData)
return ret
}
Deleting documents from the emulator keep on returning from the getMaterial function. Again until restarting the app and the emulator.
Any idea where these guest documents is saved and why it's not saving to the emulator.

related: Firebase Firestore Emulator UI is not showing any data, but data is being returned in app query
const config = {
apiKey: 'AIz....3Jk1',
projectId: 'local',
authDomain: 'app.localhost.dev',
}
Changing projectId from local to the current project getting from the command
firebase projects:list
Solved the problem

I've come across the same issue. Mine happened to be similar yet a bit different problem.
THE ISSUE
My app was part of project-1 and Firestore part of project-2.
My dumb mistake was trying to initialize Firestore - getFirestore() - with configuration for project-1 a connected it to emulator - connectFirestoreEmulator. That led to the same issues described by OP.
TL;DR
Check twice, if you are connecting to the right Firestore via getFirestore().

Related

Debugging discrepancy between authentication in firebase app and rules

I'm developing an app using Firebase Auth and Firestore.
I have the current code to create a game document:
export const createGame = async () => {
const title = makeid(6);
const myDoc = doc(db, "rides", title);
const payload = {
createdBy: auth.currentUser.uid
};
console.log(title, payload, auth.currentUser);
await setDoc(myDoc, payload);
return title;
};
This results in the following being printed to the console:
5YTm0R {createdBy: 'pLCzrgwSQSa9KxaW5OlU2l18CGY2'} UserImpl {providerId: 'firebase', proactiveRefresh: ProactiveRefresh, reloadUserInfo: {…}, reloadListener: null, uid: 'pLCzrgwSQSa9KxaW5OlU2l18CGY2', …}
As you can see from the log, the current user exists. It is an anonymous user, so isAnonymous is true when you expand the object.
However, the request fails, and when I look at the emulator's console, I see the following image:
The current user is being shown as null in the Firebase Emulator console whereas it is non-null in the application.
I'm wondering if there's a particular set of steps I need to take for Firestore to use the current user's authentication when making a request? Thanks!
Posting as community wiki:
As per #mikesol, the issue was resolved by upgrading to the newest Firebase version.
npm i firebase#latest

Uncaught TypeError: db.collection is not a function for a real-time database in firebase [duplicate]

This question already has answers here:
Firebase cannot retrieve data from database "db.collection is not a function"
(3 answers)
Closed 3 years ago.
when I try to access my collection I get the following error. My firebase app is initialized inside my main app component.
I didn't include the config object here but I know that it works because I'm also using firebase auth in my app which works perfectly fine.
App.js
componentDidMount(){
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
}
Component where I am trying to make a db call
componentDidMount(){
const db = firebase.database();
const ref = db.collection('Users/Notes').doc()
let getDoc = ref.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
}
I am rendering this component immediately by including it in App.js, I don't know if that might somehow be a problem?
You're mixing up Firebase database products.
firebase.database() gives you an object to deal with data in Firebase Realtime Database. But the code you're writing to work with that object looks like it's using the Firestore API, which is a completely different database product.
If you want an object that lets you make queries against Firestore collections, you should use firebase.firestore(), and you will need to import the library that gives you access to that API.
To be sure that you're using the correct database, please review the documentation for getting started with both Firebase Realtime Database and Firestore.
Change
const db = firebase.database();
into this:
const db = firebase.firestore();
More info Here

null returned when fetching data from firebase using expo

I'm trying to fetch data from firebase in my expo app
so this is the component where I implement this code:
import firebase from 'firebase';
// Initialize Firebase
var config = {
apiKey: "AIzaSyAVf",
authDomain: "d07f5.firebaseapp.com",
databaseURL: "https://d07f5.firebaseio.com",
projectId: "d07f5",
storageBucket: "d07f5.appspot.com",
messagingSenderId: "66392528"
};
firebase.initializeApp(config);
const api =
firebase.database().ref('/Barbers').on('value', (snapshot) => {
console.log('testing')
console.log(snapshot.val())
});
export default {
getBarbersShops,
}
when I run the app on my android device and seeing the remote debugging from the console of browser I find the " testing " word that I write in console but for this console:
console.log(snapshot.val())
I just got null for it and can't understand why?
and this is image for collection in firebase:
You're getting null because your code is accessing Firebase Realtime Database, but the picture of your data is showing it stored in Cloud Firestore. These are not the same products - they share neither the same data nor the same APIs.
doug stevensons answer is totally right! To get the document from firestore in react native, you can use the following code:
import firebase from 'react-native-firebase'
myFunction(){
firebase.firestore().collection('Barbers').doc('9R4t...').get().then(doc => {
if(doc.exists){
console.log(doc.data().name); // testing
}
}
}
or async:
async myFunctionAsync(){
const doc = await firebase.firestore().collection('Barbers').doc('9R4t...').get();
if(doc.exists){
console.log(doc.data().name); // testing
}
}

Vue/Firestore/Firebase error on retrieve data

I am creating a Vue JS app with Firestore database but have a problem somewhere in the Firestore import (probably).
Its a simple app just storing some employee details which want to be displayed (initially) to test its working. (It doesnt!) Its just using "firebase": "^5.0.4", not vue-firebase or other plugin.
Its Firestore not the Firebase Real Time db.
So in the firebaseInit.js config file are all the basic config options which are as below
import * as firebase from 'firebase'
// Initialize Firebase
var config = {
apiKey: "AIzaSyCyKS3QxqtR9HvetpT2vWKFNxa_yeRKdhA",
authDomain: "vuefsprod-fc778.firebaseapp.com",
databaseURL: "https://vuefsprod-fc778.firebaseio.com",
projectId: "vuefsprod-fc778",
storageBucket: "vuefsprod-fc778.appspot.com",
messagingSenderId: "1048509841840"
}
firebase.initializeApp(config)
var auth = firebase.auth()
var db = firebase.database()
export function signOut (callback) {
auth.signOut().then(value => {
callback()
}, err => { callback(err) })
}
export default 'firebase/firestore'
And then the script snippet to test it is as below (in Helloworld.vue)
import db from '../firebaseInit'
export default {
name: 'home',
data () {
return {
employees: [],
loading: true
}
},
created() {
db.collections('employees').get().then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc)
const data = {
}
})
})
}
}
Yarn compiles the app which displays, but there is a warning error in console as below
[Vue warn]: Error in created hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0__firebaseInit__.a.collections is not a function"
found in
---> <Home> at src/components/HelloWorld.vue
and no data is displayed to the console, there are 6 items in the employees collection.
I'm also wondering where the "a" in a.collections comes from.
Any tips on this or a better way of doing it, say with vue-firebase or other, are more than welcome. Screenshot below.
Many Thanks
You are declaring the database with the Real Time Database (RTDB) service, instead of the Firestore service:
var db = firebase.database() // <- RTDB
You should do the following instead:
var db = firebase.firestore()
Since the RTDB does not have collections, you receive the error "collections is not a function"
FYI, the different available services are documented here: https://firebase.google.com/docs/web/setup#use_firebase_services, together with how to access/declare them.
The issue is on how you retrieving data from the firebase db
db.collections('employees')
Kindly update it to
db.collection('employees')
This should resolve this .

Firestore (4.10.1): Could not reach Firestore backend. Firestore Access Issues In Cloud Functions

Quick question. Long story short, I am getting this error in my google cloud functions log:
Firestore (4.10.1): Could not reach Firestore backend.
Here is my code in my functions file:
// pull in firebase
const firebase = require('firebase');
// required
require("firebase/firestore");
// initialize firebase
const firebaseApp = firebase.initializeApp({
// Firebase configuration.
apiKey: "<Key Here>",
authDomain: "<Auth Domain>",
databaseURL: "<database url>",
projectId: "<project id>",
storageBucket: "<storage bucket>",
messagingSenderId: "<messaging sender id>"
});
// setup the firestore
var fs = firebaseApp.firestore();
exports.search = functions.https.onRequest((request, response) => {
cors(request, response, () => {
// set a reference to the foo table in firestore
var docRef = fs.collection("foo");
// check for the foo in the firestore
docRef.where('bar', '==', <something>).get().then(function(doc) {
if (!doc.docs) {
return db.collection("foo").add({
bar: <something>
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
});
});
});
At this point I am stuck. As far as I can tell, I have things set up, but maybe not? I have searched the docs and googled the issue, without much success. Do you see anything wrong?
All right. So the answer to my question is that I was not being very smart. A big thank you to Taha Azzabi for pointing me in the right direction. It turns out my problem was here:
docRef.where('bar', '==', <something>).get().then(function(doc) {
if (!doc.docs) {
return db.collection("foo").add({
bar: <something>
})
This would never work. My query was correct, but the check on doc.docs was incorrect. My code is now:
// setup the firestore
const fs = firebase.firestore();
// set a reference to the document for the searched summoner
var docRef = fs.collection("bars").doc("snickers");
// check for the bar in the firestore
return docRef.get()
.then(function(doc) {
if (!doc.docs) {
return fs.collection("bars").doc("snickers").set({
name: "snickers"
})
.then(function(reference) {
console.log("Document written");
return response.status(200).send('');
})
This is what I was looking for so I am good to go. Long story short, I was grabbing a collection of results then trying to check to see if a single result existed. What I needed to do was grab a single doc from the firestore and from there check to see if the single doc existed. However, the error:
Firestore (4.10.1): Could not reach Firestore backend.
Didn't really do a very good job at pointing me in that direction.
Did you install the Firebase CLI ?
npm install -g firebase-tools
Did you log in to the Firebase console through the CLI ?
firebase login
Did you initialize Firebase Cloud Functions ?
firebase init functions
You don't need then to reinitialize the app, initialize an admin app instance,thought.
Here's an example hope that will help
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
//trigger a function to fire when new user document created
exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate(event => {
// perform desired operations ...
});
to deployer your functions
firebase deploy --only functions
read more here https://firebase.google.com/docs/functions/get-started

Resources