So when I create a Firebase cloud function like this:
exports.create_event = functions
.region("europe-west1")
.https
.onCall((data, context) => {
... here goes my Promise ...
});
}
Then I initialize my firebase stuff inside of App.js:
import firebase from "firebase/app";
var firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
appID: "..."
};
firebase.initializeApp(firebaseConfig);
And then call it from my client app, from another class:
import firebase from "firebase/app";
import "firebase/functions";
firebase
.app()
.functions("europe-west1")
.httpsCallable("create_event")(somevalues)
.then(() => {
...
})
.catch(error => console.log(error));
I can see that it's pointing to a wrong URL when I execute code in browser. Instead of calling the url europe-west-myappid.cloudfunctions..., it actually calls following URL:
https://europe-west1-undefined.cloudfunctions.net/create_event
Instead of undefined, it should specify my app ID, or whatever it is. Am I doing a mistake somewhere?
Alright, after long hours of figuring this out, I realized that I havent created an app in Firebase console. Apparently, when you create a project, it's not yet finished - you got to create app as well, otherwise the same issue will happen to you.
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
I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.
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
}
}
I am creating a web app that uses Vue webpack with firebase. I would like to have my firebase credentials automatically change when i use firebase use <some_alias> on the firebase cli. In other projects, this simply meant including the /__/firebase/init.js file of firebase hosting. In this project, I am using the npm firebase library and can load in a specific firebase set of credentials with
import firebase from 'firebase'
var config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
firebase.initializeApp(config)
export default {
database: firebase.database,
storage: firebase.storage,
auth: firebase.auth
}
However, this does not get my credentials based on my current firebase workspace. Instead, I would like something like
import firebase from 'firebase'
const fbcli = require('firebase-tools');
export const getFirebaseInstance = () => {
return fbcli.setup.web().then(config => {
firebase.initializeApp(config)
return firebase
});
}
though synchronous. Is there any way to synchronously load in my firebase credentials?
This was solved by checking window.location.host when in the prod environment and having a production config object if the host was our production hostname and reading from the values of a configuration file otherwise.
Try using fs.writeFileSync as described in this example from a firebase blog post about reading credentials:
const fbcli = require('firebase-tools');
const fs = require('fs');
// by default, uses the current project and logged in user
fbcli.setup.web().then(config => {
fs.writeFileSync(
'build/initFirebase.js',
`firebase.initializeApp(${JSON.stringify(config)});`
);
});