Firebase JavaScript Code Complete/Intellisense - firebase

I started to develop Firebase apps and was using VSCode. I followed some on line tutorials but was unable to get code completion/intellisense working in vscode.
There seems to be nothing on the internet on this. I found a few posts but nothing work.
Such as this one: Code completion for Firebase in VS code?
Here is a sample of my code, querying a collection of document:
import { initializeApp } from 'firebase/app';
document.addEventListener("DOMContentLoaded", (evt)=> {
const app = firebase.app()
console.log(app)
const db = firebase.firestore()
const myToDoThing = db.collection("thingstodo").doc("firstthing")
//get the document
myToDoThing.get()
.then(doc=>{
const data = doc.data()
console.log(data)
//console.log(data.createAt )
})
//Get live update of the document
myToDoThing.onSnapshot(doc=>{
const data = doc.data()
console.log(data)
})
})

Related

Unable to create a new collection or document Firestore

I have been trying to connect my web app to Firebase in order to save some input data into a Firestore database. I used Firebase a few months ago and everything was fine but now when I try to link it to a new project I'm unable to do anything. From the console, when I start a new collection, I can't save it and if I do it directly from my web app nothing is happening and then I get an error message :
#firebase/firestore: Firestore (9.8.4): Connection WebChannel transport errored
I saw such question on here but the only solutions given were either a service outage or that after a few refresh it might work but I have been trying for a few days now and I'm still unable to do anything
Don't know if it is very relevant as the issue is also in the firebase console but here's my firebase config
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
//
};
export const app = initializeApp(firebaseConfig);
export const database = getFirestore(app);
const collectionRef = collection(database, "userID");
const handleClick = () => {
addDoc(collectionRef, { title })
.then(() => console.log("Data Added"))
.catch((err) => console.log(err.message));
};

Firebase Storage with Google Actions

I am having some issues connecting my firebase storage with my google action. I need to be able to "download" the json files inside in order to be able to read and pick out what a user may need given data that they provide when they call the action.
Below is the code that I currently have, complied from the different APIs and other stackoverflow questions I have found.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const Firestore = require('#google-cloud/firestore');
const firestore = new Firestore();
var storage = require('#google-cloud/storage');
const gcs = storage({projectId: 'aur-healthcare-group'});
const bucket = gcs.bucket('gs://aur-healthcare-group');
admin.storage().bucket().file('aur-healthcare-group/aur_members.json').download(function(errr, contents){
if(!err){
var jsObjext = JSON.parse(contents.toString('utf8'));
}
});
The current error I am receiving is "code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause. When I check the logs I only get the above mentioned message again.
I believe that I am not accessing my firebase storage correctly and have trouble finding a good resource on how to access this correctly. Would somebody be able to give me an example of how to access the storage correctly so I will be able to apply it to my project?
Since you're running in Firebase Functions, you shouldn't need to require the #google-cloud/storage dependency directly. Rather, you can get the correctly authenticated storage component via admin.storage()
Following that, you shouldn't download the file to your function, as you would be better off reading directly into memory via a readStream.
With regards to your existing code error, it may be because you're checking if (!err) when the callback variable is errr.
I've done this in the past and here's a code snippet of how I achieved it. It's written in Typescript specifically, but I think you should be able to port it to JS if you're using that directly.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
import { Bucket } from '#google-cloud/storage';
admin.initializeApp()
const db = admin.firestore()
const bucket = admin.storage().bucket('project-id.appspot.com') // Use your project-id here.
const readFile = async (bucket: Bucket, fileName: string) => {
const stream = bucket.file(fileName).createReadStream();
return new Promise((resolve, reject) => {
let buffer = '';
stream.on('data', function(d: string) {
buffer += d;
}).on('end', function() {
resolve(buffer)
});
})
}
app.handle('my-intent-handler', async (conv) => {
const contents = await readArticle(bucket, 'filename.txt')
conv.add(`Your content is ${contents}`)
})
exports.fulfillment = functions.https.onRequest(app)

Is Firebase Firestore working in React Native Expo?

I found out some documentation in official expo forum about firestore and everything seems to be working. And I were able to implement whole login, sign up flow with various providers from firebase. But I can not run any query from firestore. I am doing it like this:
const[dataSource, setDataSource] = React.useState({});
const getMealTypes = (mealTypes) =>{
const Meals = [];
mealTypes.get().then(function (doc) {
if (doc.exists) {
const {title, count} = doc.data();
Meals.push({
key: doc.id,
title,
count
})
} else {
console.log("No such document!");
}
}).catch(function (error) {
console.log("Error getting document:", error);
});
console.log(Meals);
setDataSource(Meals);
}
React.useEffect(() => {
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
const mealTypes = firebase.firestore().collection('mealTypes');
getMealTypes(mealTypes);
setDataSource([]);
}, []);
I have tried many more ways to get that response, but it never go into promise after get() function. Is get() broken in expo or am I doing something wrong?
Any help would be appreciated!
what version of firebase? there was a regression in support for react-native in the javascript sdk for firebase recently and the team is working on resolving that, until then i would recommend using version 7.9.0, which you will get if you run expo install firebase with the latest version of expo installed in your project

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

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