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 .
Related
I am using Next.js to fetch data from my Firestore Database, but I keep getting an error in the console, stating that GET (FirestoreDatabaseURL) 404 (not found).
When I try any other json database such as myfakestore or jsonplaceholder, my code works (I tried both getServerSideProps and fetching with UseState), works beautifully. But not from my own database. Tried with Postman, but it won't work either.
I have tried to find different ways to get the database URL, but I am only finding this one format:
https://PROJECTID.firebaseio.com
The server is in us-central, which also helps determine the URL.
While testing around, I have gotten the error FetchError: invalid json response body at https://PROJECTID.firebaseio.com/ reason: Unexpected token F in JSON at position 0
Which I came to find out that it's not actually returning json, but HTML.
Just for context, this is my working code:
const [showProducts, setShowProducts] = useState()
const apiData = 'https://celeste-73695.firebaseio.com/'
let displayProducts
function pullJson () {
fetch(apiData)
.then(response => response.json())
.then(responseData => {
displayProducts = responseData.map(function(product){
return (
<p key={product.id}>{product.title}</p>
)
})
console.log(responseData)
setShowProducts(displayProducts)
})
//return
}
useEffect(() => {
pullJson()
},[])
And my firebase.js file
import firebase from 'firebase';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
export default db;
Can anybody point me in the right direction?
Thanks in advance.
The databaseURL property is for the Firebase Realtime Database, which you probably didn't create yet. The databaseURL property is not necessary to use Firestore though, so you should be able to access that with just the configuration data you have.
You may have created the realtime database but not have configured it with firebase config. I recommend you to go through this documentations for the realtime database.
To configure the firebase firestore you need to do the following:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
And make sure to export the db reference as will be used in your project.
After that you can start using the firestore like documented here as you have tried to use it with URL you may have to change the implementation for using it like shown in above documentations
On a firebase.js file I am doing this:
import firebase from "firebase/app";
import "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
databaseURL: process.env.DATABASEURL,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID,
appId: process.env.APPID,
measurementId: process.env.MEASUREMENTID
};
export function firebaseDB() {
// Initialize Firebase
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
// firebase.analytics();
}
return firebase;
}
Then, on pages/index.js I am using the getInitialProps:
App.getInitialProps = async () => {
const firebaseDatabase = await firebaseDB();
const db = firebaseDatabase.firestore();
let result;
db.collection("users")
.add({
first: "Ada",
last: "Lovelace",
born: 1815
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
result = { docs: docRef };
})
.catch(function(error) {
console.error("Error adding document: ", error);
result = { error: error };
});
return result
};
I am assuming that because of the asynchronous nature I am returning the result variable undefined and getting this error:
"App.getInitialProps()" should resolve to an object. But found "undefined" instead.
So, I am not happy with the way I am configuring this...can someone throw some light?
Here are some of the ways I can think of:
Create an HOC for it and wrap the page components that will be using it. (https://medium.com/#uvictor/simple-firebase-authentication-with-next-js-using-hoc-higher-order-components-8e8931d25cfa)
Initialise it in the Root component and pass the DB ref to the children. For example, in your Root component, you declare your routes there. What you wanna do is pass the DB ref to each of the components under it. Though this might be problematic when you wanna do SSR. Not sure how would this play out.
If only a single page will be using Firebase (happened to me a couple of times), just do it like what you are doing right now.
If you are thinking of using Redux, you might want to initialise firebase and bind it to the store (https://github.com/prescottprue/react-redux-firebase)
My suggestion is, try not to overcomplicate it. Do what works for you.
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
}
}
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
I'm starting with vue and firebase, but now I have this error when I show what I already have in my database.
main.js
import vueFire from 'vuefire';
import firebase from 'firebase';
Vue.use(vueFire);
let config = {
apiKey: "mykey",
authDomain: "mydomain",
databaseURL: "myurl",
projectId: "my",
storageBucket: "bucket",
messagingSenderId: "number"
};
let application = firebase.initializeApp(config)
let db = application.database()
let notificationsdb = db.ref('notifications')
export { notificationsdb };
component.vue
import { notificationsdb } from '../main';
export default {
name: 'Notifications',
firebase: {
notifi: notificationsdb
},
data() {
return{
newNoti: {
name: '',
text: ''
},
}
},
methods: {
addNoti: function(){
notificationsdb.push(this.newNoti);
this.newNoti.name = '',
this.newNoti.text = ''
toastr.success('Notificación creada');
},
deleteNoti: function(noti){
notificationsdb.child(noti['.key']).remove();
toastr.success('Notificación eliminada');
}
}
}
If I delete this line of code and save it and then put it back, I keep changes, it works. But if I press F5 it stops working
firebase: {
notifi: notificationsdb
},
and he sent me the following error
[Vue warn]: Error in created hook: "Error: VueFire: invalid Firebase binding source."
So, I'm assuming you started your project with something like:
vue init webpack myProject
Basically what's happening is your component doesn't have access to the data from firebase the first time you load it. It takes some time for you to make an edit (time in which the server request is completing). Then when you press save, it triggers the HMR, and your site reloads with the data it's expecting.
Try making these changes (although you should move this config stuff into a separate file (like firebaseDB.js for example)):
// let db = application.database()
// let notificationsdb = db.ref('notifications')
// export { notificationsdb }
export default application.database()
Then in component.vue:
[...]
import db from '../firebaseDB'
[...]
firebase: {
notifi: db.ref('notifications')
},
[...]
You'll probably want to add a loading state var to this component, and so on. Good luck!