Using with Firebase / Expo query to Cloud Firestore - firebase

So I am trying to keep my code clean and build different files for querying... So I may be taking this harder than it needs to be.
I building a react-native app using Expo CLI.
I have created 3 files, one is my firebase config file,
one is a query file
then the actual file that is using that query.
it looks ok to me... but I get this error.
TypeError: undefined is not an object(evaluating'_firebase.firebase.firestore')
Here is my config file
import * as firebase from "firebase";
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
appId: "app-id",
measurementId: "G-measurement-id"
};
firebase.initializeApp(firebaseConfig);
Then I have a a query file, basically acting as the API layer
import { firebase } from "./firebase";
const db = firebase.firestore();
const getListings = () => {
db.collection("listings").get();
};
export default {
getListings,
};
Then I am trying to view the queried data.
import listingApi from "../api/listings";
function ListingsScreen({ navigation }) {
const [listings, setListings] = useState([]);
useEffect(() => {
loadListings();
}, []);
const loadListings = async () => {
const response = await listingApi.getListings();
setListings(response.data);
};
This is my first time ever using Firebase or cloud firestore... so im really confused.

The error message is telling you that '_firebase.firebase.firestore' data is returning as undefined, this means the document you requested doesn't exist.
At the officiald documentation of Expo, is recommended to put the firebase config information in the same file with your code in order to use firebase, for example:
import * as firebase from 'firebase'
import 'firebase/firestore';
const firebaseConfig = { ... } // apiKey, authDomain, etc. (see above)
firebase.initializeApp(firebaseConfig);
const dbh = firebase.firestore();
dbh.collection("characters").doc("mario").set({
employment: "plumber",
outfitColor: "red",
specialAttack: "fireball"
})

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

"Firebase Error : Firestore has already been started and its settings can no longer be changed." connecting Firebase v9 with Firestore Emulator

I have updated to Firebase v9 a few weeks ago and I have an issue when trying to connect my Firebase App to Firestore Emulator.
firebase.js (my VueJS plugin, where I setup Firebase) :
import { initializeApp, getApps } from "firebase/app"
import { getAuth, connectAuthEmulator, onAuthStateChanged } from "firebase/auth";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore"
import { getStorage, connectStorageEmulator } from "firebase/storage";
import { getFunctions, connectFunctionsEmulator } from 'firebase/functions';
import { isSupported, getAnalytics } from "firebase/analytics";
export default async ({ app }, inject) => {
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SERVICE_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
}
// I've checked, the values of firebaseConfig are all set here.
// This IF statement is here to avoid initializing the app several times
const apps = getApps();
let firebaseApp = null;
if (!apps.length) {
firebaseApp = initializeApp(firebaseConfig);
}
else {
firebaseApp = apps[0];
}
// INIT AUTH
const auth = getAuth();
auth.languageCode = 'fr';
onAuthStateChanged(auth, async authUser => {
const claims = authUser ? (await authUser.getIdTokenResult(true)).claims : null;
await app.store.dispatch('onAuthStateChanged', { authUser, claims });
},
(error) => {
console.error("Firebase Auth onAuthStateChanged ERROR", error)
});
// Get other services
const firestore = getFirestore(firebaseApp);
const storage = getStorage(firebaseApp);
const functions = getFunctions(firebaseApp, process.env.FIREBASE_REGION);
// Setup analytics if supported
let analytics = null;
const analyticsSupported = await isSupported()
if (analyticsSupported) {
analytics = getAnalytics();
analytics.automaticDataCollectionEnabled = false;
}
// Connecting to emulators
if (process.client && process.env.APP_ENV === 'local') {
console.log("LOCAL ENVIRONMENT, CONNECTING TO EMULATORS...");
connectAuthEmulator(auth, "http://localhost:9099");
connectFirestoreEmulator(firestore, 'localhost', 8080);
connectStorageEmulator(storage, "localhost", 9199);
connectFunctionsEmulator(functions, "localhost", 5001);
}
Inject firebase objects into my VueJS app
const fire = { auth, firestore, storage, functions, analytics }
inject('fire', fire);
}
Here is the error I get, caused by this line : connectFirestoreEmulator(firestore, 'localhost', 8080);
FirebaseError Firestore has already been started and its settings can
no longer be changed. You can only modify settings before calling any
other methods on a Firestore object.
I am not trying to modify Firestore object's settings property myself, so it has to be the method connectFirestoreEmulator.
The problem can be narrowed down to the following code :
import { initializeApp } from "firebase/app"
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore"
export default async ({ app }, inject) => {
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SERVICE_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
}
firebaseApp = initializeApp(firebaseConfig);
const firestore = getFirestore(firebaseApp);
if (process.env.APP_ENV === 'local') {
connectFirestoreEmulator(firestore, 'localhost', 8080);
}
const fire = { auth, firestore, storage, functions, analytics };
inject('fire', fire);
}
I've managed to avoid triggering the error by adding process.client so it doesn't connect to emulators on server-side (SSR) :
if (process.client && process.env.APP_ENV === 'local') {
However when I add that, the emulators are not connected when code is executed server-side (SSR) on the first page load, and initial Firestore data is being read from the real Firebase App instead of the emulators.
Any idea what can be done to manage proper connection to Firestore emulator on SSR ?
Is this a Firebase bug ?
Versions I use :
In my App : Firebase JS SDK v9.6.9
Emulators : firebase-tools v10.4.0 for the emulators
What I've already read/tried :
https://firebase.google.com/docs/reference/js/app.md#initializeapp
Firebase Firestore emulator error `Host has been set in both settings() and useEmulator(), emulator host will be used`
FirebaseFirestore has already been started and its settings can no longer be changed
It's been a while, but I ran into a similar issue, and after a lot of hairpulling, I ended up with a solution (though it feels a little hacky).
Before running the connectFirestoreEmulator line, check if firestor._settingsFrozen is false. So you only run that line basically if Firestore hasn't already been initialized. You can check that firestore is getting initialized with the emulator settings by logging out the firestore variable before the connectFirestoreEmulator line and seeing what the settings say there--if it says port is 8080 and host is localhost, then you're good.
Here's my code for comparison (slightly different setup from yours but I believe we were running into the same issue):
import { initializeApp } from 'firebase/app';
import { connectAuthEmulator, getAuth } from 'firebase/auth';
import { connectFirestoreEmulator, getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: "XXXXXXXXX",
authDomain: "XXXXXXXXX",
projectId: "XXXXXXXXX",
storageBucket: "XXXXXXXXX",
messagingSenderId: "XXXXXXXXX",
appId: "XXXXXXXXX",
measurementId: "XXXXXXXXX",
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);
export default (context) => {
if (context.env.appEnv === 'dev') {
connectAuthEmulator(auth, `http://127.0.0.1:${context.env.authPort}`);
if (!db._settingsFrozen) {
connectFirestoreEmulator(db, '127.0.0.1', parseInt(context.env.firestorePort));
}
}
}
Reviewing Firebase JS SDK issues related, it seems that the issue is because the Firestore instance (which is initialized like this: firestore = getFirestore(firebaseApp)) is called after the emulator (connectFirestoreEmulator) has been started.
After calling the "connectFirestoreEmulator" method, "firestore" variable is being used in the constant variable "fire = { auth, firestore, storage, functions, analytics }"
If you use "const fire" before connecting to the emulator, the problem may be solved.
Here is a code example that might help you:
firebaseApp = initializeApp(firebaseConfig);
const fire = { auth, firestore, storage, functions, analytics };
const firestore = getFirestore(firebaseApp);
if (process.env.APP_ENV === 'local') {
connectFirestoreEmulator(firestore, 'localhost', 8080);
}
As a reference, I used this github repository.
You can try checking the setting.host value of your firebase object in order to check if it is already 'localhost', so you can skip calling the connectFirestoreEmulator() function.
This did happen to me in an Angular application using Hot Module Replacement. I tried to use a global constant, but did not work.
In my case, I'm using AngularFire (https://github.com/angular/angularfire), so I had to do something like this:
// ...
const firestore = getFirestore();
const host = (firestore.toJSON() as { settings?: { host?: string } }).settings?.host ?? '';
// console.log({ host });
if (process.env.APP_ENV === 'local' && !host.startsWith('localhost')) {
connectFirestoreEmulator(firestore, 'localhost', 8080);
}
// ...
In my case I had to use firestore.toJSON() in order to access the settings property, check how it is in your case.

Error importing firebase to React Native Expo

I want to authorize the FireBase application in React Native Expo, but I have an error.
I am using FireBase version 8.2.34 ( installed with the command "npm install firebase#8.2.3" ).
Code ( firebase.js ) :
// Import the functions you need from the SDKs you need
import * as firebase from "firebase";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = { ... };
// Initialize Firebase
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app()
}
ExpoGO App error ( in line №2 ):
Uncaught Error
Can't find variable: IDBIndex
...
<global>
...\firebase.js:2
...
UPD:
Also, I have a problem with importing FireStore.
Note:use compat while importing.
i suggest to have these in one seprate file. (use web configuration)
import firebase from 'firebase/compat/app';
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = firebase.initializeApp(firebaseConfig);
export const db = app.firestore();

Nuxt + Firebase - Correct way to handle environment variables

I have been trying to develop a fully functional, reusable firebase authentication app however after looking online at multiple different solutions, I have developed the below which works perfectly but from my understanding there is no way to protect the API keys/sensitive data? Is there anyway to use environment variables on the plugins/firebase.js file?
The nuxt/firebase docs suggests declaring them within the nuxt.config.js file? But when following the docs and trying to install firebase & #nuxtjs/firebase I keep running into errors. NPM error when I am trying to install #nuxtjs/firebase
Is there any definitive/working best practise to follow when working with Nuxt & Firebase?
~plugins/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore'
import 'firebase/storage'
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
export const auth = firebase.auth()
export const google = new firebase.auth.GoogleAuthProvider()
export const storage = firebase.storage()
export default firebase
~/plugins/fireauth.js
import { auth } from '~/plugins/firebase.js'
export default (context) => {
const { store } = context
return new Promise((resolve, reject) => {
auth.onAuthStateChanged(user => {
console.log(user);
store.dispatch('setUser', user)
resolve(user)
}, err => {
reject(err)
})
})
}
Update to #Kissu
The environment variables are now working as per #kissu's comments below - however the app is now crashing because the initializeApp() is not being run.
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
~/plugins/firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
import 'firebase/compat/storage'
export default ({ $config }) => {
const firebaseConfig = {
apiKey: $config.firebaseConfig.apiKey,
authDomain: $config.firebaseConfig.authDomain,
projectId: $config.firebaseConfig.projectId,
storageBucket: $config.firebaseConfig.storageBucket,
messagingSenderId: $config.firebaseConfig.messagingSenderId,
appId: $config.firebaseConfig.appId
}
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
}
export const auth = firebase.auth()
export const google = new firebase.auth.GoogleAuthProvider()
export const storage = firebase.storage()
Resources:
https://firebase.nuxtjs.org/
https://dev.to/drewclem/building-user-accounts-with-nuxt-vuex-and-firebase-2o6l
In your Firebase Config, you can use local environment variables (from your .env file) using process.env.VUE_APP_:
// ~/plugins/firebase.js
const firebaseConfig = {
apiKey: process.env.VUE_APP_FIREBASE_apiKey,
authDomain: process.env.VUE_APP_FIREBASE_authDomain,
projectId: process.env.VUE_APP_FIREBASE_projectId,
storageBucket: process.env.VUE_APP_FIREBASE_storageBucket,
messagingSenderId: process.env.VUE_APP_FIREBASE_messagingSenderId,
appId: process.env.VUE_APP_FIREBASE_appId,
measurementId: process.env.VUE_APP_FIREBASE_measurementd,
};
But be sure to set your Variables in your .env file like this:
// ~/.env
// NOTE: THIS FILE IS NOT COMMITTED TO CODE REPOSITORY / GITHUB AND SHOULD BE IGNORED BY DEFAULT IN YOUR `.gitignore` FILE
// NOTE: For Vue.js environment variables, you must prefix them with `VUE_APP_`
VUE_APP_FIREBASE_apiKey=
VUE_APP_FIREBASE_authDomain=
VUE_APP_FIREBASE_projectId=
VUE_APP_FIREBASE_storageBucket=
VUE_APP_FIREBASE_messagingSenderId=
VUE_APP_FIREBASE_appId=
VUE_APP_FIREBASE_measurementId=
Where after the = you put your secret keys and ID's. NOTE: Be sure to leave NO SPACE between the = and your key. For example:
VUE_APP_FIREBASE_apiKey=YOUR.KEY.HERE
...
You can read more documentation on VUE_APP Environment Variables here: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
This .env file should not be committed to Github, or your code repository. Instead, set these variables on your production environment. For example, if you are using Netlify or Heroku, you will want to set Environment Variables with the EXACT same names like VUE_APP_FIREBASE_apiKey and set its value to be equal to your Key.
If using Netlify, set your Environment Variables in your Build & Deploy Site Settings:
https://app.netlify.com/sites/{{YOUR_SITE_HERE}}/settings/deploys#environment

I can't add data from my vue.js page to firestore database

I am new to vue.js and firebase
I want to add a collection to my firebase/firestore database from my Vue page
Here's my code:
<script>
import db from '#/fb'
export default {
methods: {
addTask(){
const project = {
title: 'some title',
content:'some content',
due:'01/01/2021',
person: 'someone',
status:'ongoiing'
}
db.collection('projects').add(project).then(() => {
console.log('added to database')
})
...
and this is my firestore project configuration that I put in the 'fb.js' file on the 'src' folder:
//import firebase from 'firebase'
import firebase from 'firebase/app'
import 'firebase/firestore'
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "XXXXXX",
authDomain: "XXXX.firebaseapp.com",
projectId: "XXXXX",
storageBucket: "XXXXX.appspot.com",
messagingSenderId: "XXXXXXXX",
appId: "1:XXX:web:XXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
db.settings({timestampsInSnapshots:true})
export default db;
My problem is when I click on the add button, nothing happens
Thanks a lot for the help

Resources