'Cannot read property 'apps' of undefined' in nuxtJs/ firebase - javascript

I have tried to integrate firebase with Nuxt Js and i am getting this error
As per documentation first I have installed firebase with help of "npm install firebase" and then i have installed "npm install #nuxtjs/firebase" and third i have integrated my firebase config in modules in nuxt.config.js
so whats the solution to solve the above error?
Thanks in advance

It depends on which version of #nuxtjs/firebase you are using, because this package #nuxtjs/firebase is not compatible with firebase version 9+ supporting tree-shaking.
So you need to downgrade you package to firebase version 8 and prior.
For more information, please check the authors github issues.

If you are using the new Modular SDK v9.0.1 you might get the above error as it does not use firebase. namespace now,
Try using getApps() instead of firebase.apps.
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
const firebaseConfig = {...}
if (!getApps().length) {
//....
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app) export {db, auth}

I banged my head against this problem for a while - I was trying to use the Realtime Database in a dynamic page and getting the same error. I finally went back to this issue on the firebase module repo. Basically I had to do two things:
use the async asyncData method instead of just defining data properties; and
use both the app and params variables.
So instead of this:
export default {
data: () => ({
items: []
)},
async fetch ({ params }) {
const ref = this.$fire.database.ref(`foo/${params.slug}`)
const data = (await ref.once('value')).val()
this.items = data
}
}
I had to do this:
export default {
async asyncData ({ app, params }) {
const ref = app.$fire.database.ref(`foo/${params.slug}`)
const data = (await ref.once('value')).val()
return { items: data }
}
}

Related

Having trouble getting database connected to frontend and am getting an error

Hi I'm trying to get my firebase database connected to my vue frontend but when I try to do that I get the following error.
Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/firebase_app.js?v=42c663d6' does not provide an export named 'default'
Here is the code its refering to.
import { projectFirestore } from "../Firebase/Config";
const getPremium = () => {
const profiles = ref([])
const error = ref(null)
const load = async () => {
try{
const res = await projectFirestore.collection('profiles').get()
profiles.value = res.docs.map(doc => {
// console.log(doc.data())
return {...doc.data(), id: doc.id}
})
}
catch (err){
error.value = err.message
console.log(error.value)
}
}
return { profiles, error, load}
}
export default getPremium
I have seen similar questions regarding this but adding to the vite.config.js doesn't work and to be honest I'm a bit confused as to what the actual problem is as I'm new to this and I think it might be that it can't find where to export getPremium from but could be completely wrong if someone could explain whats going wrong it would be a great help thanks.
You may import firebase module like ↓
import firebase from 'firebase/app'
As you can see, in firebase_app.js uses export { ... } (named export), so if you want to use some functions in this module, you need to used named import
Something like import { xxx } from 'xxx'
NOTE
In firebase v9, you can import module looks like ↓
// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
Have a look at official migration docs

Optimized Way To Initialized Firebase in React Native

During building an app, I couldn't be able to initialized firebase V9 in optimized form in expo react native. I switch from V8 to V9 And counter different error, which aren't making sense to me.
Like module idb missing from file "...\node_modules\#firebase\app\dist\esm\... even I create a metro.config.js File.
And Firebase could not be found within the project when it is present in (Firebase V8).
And this error, idk what's that about at node_modules\react-native\Libraries\LogBox\LogBox.js:149:8 in register.
Error at node_modules\react-native\Libraries\LogBox\LogBox.js:60:8 in errorImpl.... , here's the issue or check this problem
And undefined is not an object (evaluating '_app.default.apps').
All such questions and their answers are available on stackoverflow. But none of them work for me. And Im not elaborating these issues, just giving you idea. So I try some things, and it worked.
In above question, I tell about some errors and after many searching I was able to fixed my problem.
First, I delete .expo , .expo-share , node_modules , package-lock.json , and yarn.lock (if you have). Then yarn install or npm install.
Second, change the firebase code to this for V9. As I see many people suggesting to downgrade to V8 when above mentioned errors occurs when they don't need to.
import { initializeApp, getApps, getApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
// import others as you need
const firebaseConfig = { ... };
let app;
if (getApps().length === 0) app = initializeApp(firebaseConfig);
else app = getApp();
const db = getFirestore(app);
const auth = getAuth();
export { auth, db };
For V8
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
// import others as you need
const firebaseConfig = { ... };
let app;
if (firebase.apps.length === 0) app = firebase.initializeApp(firebaseConfig);
else app = firebase.app();
const db = app.firestore();
const auth = firebase.auth();
export { auth, db };
I mentioned about creating a metro.config.js, as I read comments in this problem, some are confusing is there problem related to firebase or metro file. For me, I guess its firebase. If still you get this error, then downgrade your to firebase#9.6.11, see here
I give reference of 2 errors, and other 2 are easily available. It work for me, I hope this will help anyone of you.

"Field Value is not a function" when I try to use the increment feature

I am trying to implement some simple thumbs up/thumbs down functionality in a react app using cloud firestore. The app lets users search for movies and give it a thumbs up or down, and then I want to increment the value in my frestore database. When I try to do this I'm given the error "FieldValue is not a function".
Here is my code in the component:
import {db}from './firebase'
const firebase = require("firebase/firestore");
const movieDocRef = db.collection("ratings").doc(title);
const increment = firebase.FieldValue.increment(1);
movieDocRef.update({thumbsUP: increment})
And here is my firebase config file
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
const config = {
//my config data all should fine
};
export const fire = firebase.initializeApp(config);
export const db = fire.firestore();
Would appreciate any help you can give. I've looked at a few similar topics and nothing seems to have resolved this
Since you are using react, I suggest reviewing the documentation for getting started with Firebase using module bundlers. Your imports should look more like this when using version 8.0.0 or later of the Firebase SDKs:
import firebase from "firebase/app";
import "firebase/firestore"
const movieDocRef = firebase.firestore().collection("ratings").doc(title);
movieDocRef.update({ thumbsUP: firebase.firestore.FieldValue.increment(1) })

Importing js to Vue project

I'm looking at using Vuefire to make integrating Firestore with my Vue project easier. When reading the getting started documentation, they have you create a db.js file so that you can "conveniently" import it anywhere in your project.
import firebase from 'firebase/app'
import 'firebase/firestore'
// Get a Firestore instance
export const db = firebase
.initializeApp({ projectId: 'MY PROJECT ID' })
.firestore()
// Export types that exists in Firestore
// This is not always necessary, but it's used in other examples
const { Timestamp, GeoPoint } = firebase.firestore
export { Timestamp, GeoPoint }
// if using Firebase JS SDK < 5.8.0
db.settings({ timestampsInSnapshots: true })
On the next step in the Binding page they show you can import that module into a "RecentDocuments" component
// RecentDocuments.vue
import { db } from './db'
export default {
data() {
return {
documents: [],
}
},
firestore: {
documents: db.collection('documents'),
},
}
If I import that same db.js file into another component, won't it create another instance of the firebase firestore object, because it's basically calling .initializeApp again?
// SomeOtherComponent.vue
import { db } from './db'
export default {
...
Or am I not understanding how imports work?
No, it won't. Imports only happen once. The exports that come from each import are effectively singletons. You should be able to verify this by simply adding log messages to the import.

How to unit test a function that depends on Firebase reference?

I want to unit test a function in my application that calls and updates a Firebase reference. The problem I am facing is that when I try to run the test and import the file that contains the function, I get the following error SyntaxError: Unexpected token u in JSON at position 0 which points to the line in my function file that imports my reference to Firebase.
I am using Webpack and Babel on this project, so I tried setting a resolve.alias in the webpack.config file which worked when the application was running, but did not work when I ran npm test. At this point I'm at a loss as to how I can mock out the Firebase reference so I can test the other functions of the function. Here's some sample code:
constants/index.js
import firebase from 'firebase';
const firebaseConfig = JSON.parse(unescape(`${config.FIREBASE_CONFIG}`));
const mainApp = firebase.initializeApp(firebaseConfig);
export const ref = mainApp.database().ref();
actions/settings.js
import * as actions from './';
import { ref } from '../constants';
export const updateSetting = (e, value) =>
(dispatch) => {
ref.child('setting')
.set(value)
.then(() => {
dispatch(actions.confirmFBSave());
})
.catch((err) => {
dispatch(actions.failFBSave({ text: err.code }));
});
};
What testing framework are you using Qunit, jasmine, mocha? With AngularFire and Angular it is much easier because you can pass a mock class in at DI, but I have also tested non angular js for server side. Then I used Sinon to get mock initializeApp and return a Mock firebase app.
You could also try https://github.com/thlorenz/proxyquire I didn't need to go that far, but I have seen it suggested. That way you are essentially intercepting the import and swap it out for something you can test with.

Categories

Resources