Expo Snack: _firebase.default.firestore is not a function - firebase

I made a service in my React Native Expo Snack app that handles the instantiation of different firebase services. Somehow, Snack isn't able to find firestore, as it says "_firebase.default.firestore is not a function". The code used is shows below:
import firebase, { firestore } from 'firebase';
const config = { ... // Deleted, assume the config is correct }
export const FirebaseApp = !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();
export const Firestore = firebase.firestore();
export const Auth = firebase.auth();
Can somebody confirm this should work in Snack? Why doesn't it recognize firestore() as a function?

Related

Fetching from Firestore URL shows 404 - URL not right?

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

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 callable functions, unsure about client code, getting internal error

I have been trying to get firebase functions to work for a day but failing miserably.
I have set up a http cloud function from the google cloud functions inline editor with code:
const admin = require('firebase-admin');
const functions = require('firebase-functions')
admin.initializeApp();
const db = admin.firestore();
exports.account_create_callable = functions.https.onCall((data,context) => {
var docRef = db.collection('users').doc(context.auth.uid)
docRef.set(
{
createdAt:Date.now(),
}, { merge: true }
);
return
})
I'm using React and there is very limited documentation but I've put together what I think is correct:
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import "firebase/functions";
const firebase = firebase.initializeApp({
apiKey: process.env.REACT_APP_FB_API_KEY,
authDomain: process.env.REACT_APP_FB_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FB_PROJECT_ID,
});
const firestore = firebase.firestore();
// require('firebase-functions'); // I saw this is some documentation but don't think it's needed?
const functions = firebase.functions()
export function createUser(uid, data) {
const account_create_callable = functions().httpsCallable('account_create_callable')
account_create_callable()
}
However when I run this code, I get an internal error shown in the browser console.
Error: internal
at new HttpsErrorImpl (error.ts:65)
at _errorForResponse (error.ts:175)
at Service.<anonymous> (service.ts:276)
at step (tslib.es6.js:100)
at Object.next (tslib.es6.js:81)
at fulfilled (tslib.es6.js:71)
Interestingly, I get the same error when I call a non existent function like so:
functions().httpsCallable('asdf')
Would appreciate if someone could let me know where I'm going wrong.
My Firebase SDK is up to date.
I set up the function in the inline editor and set my region to eu-west 2, would this have any effect on my client code?
Since your Callable Function is deployed on europe-west2, you must initialize your client SDK with the appropriate region:
var functions = firebase.app().functions('europe-west2');
See https://firebase.google.com/docs/functions/locations#client-side_location_selection_for_callable_functions.

Implement callable cloud functions in Firebase client app

I have recently discovered the Firebase callable functions which allows me to call HTTPS trigger like function from the client side (and with auth() support).
I struggle to implement this new feature in my already existing Firebase web-client application.
I have some cloud functions running, among them are some HTTPS functions I would like to transform into an HTTPS callable function (with functions.https.onCall).
The documentation indicates:
Set up your client development environment
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-functions.js"></script>
And my code is:
import firebase from 'firebase';
import 'firebase/firestore';
const firebaseApp = firebase.initializeApp({
apiKey: '....',
authDomain: '....',
databaseURL: '....',
projectId: '....',
storageBucket: '....',
messagingSenderId: '....',
});
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const functions = firebaseApp.functions();
export { db, auth, functions };
When I run my app, I got the following error:
Uncaught TypeError: firebaseApp.functions is not a function
I have tried yarn add firebase-functions and then import 'firebase-functions but then the app requires firebase-admin. I am affraid it is too much for a client-app so I might go in the wrong direction.
Can someone help me with this issue?
(!) This issue is NOT about the server-side Firebase SDK for Cloud Functions (Node JS). It is about calling Cloud functions directly from a Firebase web app.
Thank you!
UPDATE:
Thanks to #Andrew's post, this solves my issue:
My configuration
import firebase from 'firebase';
import 'firebase/firestore';
import '#firebase/functions';
import firestoreConfig from '#/config/firestore';
const firebaseApp = firebase.initializeApp(firestoreConfig /* The JSON configuration from my Firebase project */);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const functions = firebaseApp.functions();
export { db, auth, functions };
Using the configuration:
import { db, functions } from '#/database/firestoreInit';
export default {
addMessage(text) {
const addMessage = functions.httpsCallable('addMessage');
return addMessage({ text }).then(result => result);
},
}
I just ran into this same problem myself and solved it by installing and importing the #firebase/functions npm package. I found the solution on github here:
https://github.com/firebase/firebase-js-sdk/blob/master/packages/functions/README.md
From the README on github:
ES Modules
import firebase from '#firebase/app';
import '#firebase/functions'
// Do stuff w/ `firebase` and `firebase.functions`
CommonJS Modules
const firebase = require('#firebase/app').default;
require('#firebase/functions');
// Do stuff with `firebase` and `firebase.functions`
Hope that helps! The actual documentation is not very clear about having to do this in order to call the functions.
About #firebase/functions:
This package is not intended for direct usage, and should only be used via the officially supported firebase package.
This worked for me:
import * as firebase from 'firebase/app'; // Typescript
// import firebase from 'firebase/app'; // JS
import 'firebase/functions';
const myCallableFunc = firebase.functions().httpsCallable('myCallableFunc');
I don't know about importing firebase-functions with a CDN but if you're using npm then you don't need the firebase-functions package, just installing firebase will do.
Follow the steps mentioned here. Firebase cloud functions
I think there is nothing like firebaseApp.functions.

react-boilerplate not working with firebase

I have imported firebase like this,
import * as firebase from 'firebase';
const config = {
};
firebase.initializeApp(config);
export const database = firebase.database().ref('/posts');
Then I got this error:
__WEBPACK_IMPORTED_MODULE_0_firebase_app__.database is not a function
so I tried this way.
const firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
Then I got this error.
firebase.initializeApp is not a function
Does anyone know how to work with server side rendered react with webpack, firebase ?
Thanks.
instead of
export const database = firebase.database().ref('/posts')
try :
const database = firebase.database().ref('/posts')
module.exports = database

Resources