Importing js to Vue project - javascript

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.

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

ReferenceError: Can't find variable: firebase . I can not connect the App to Firebase from Expo?

I am trying to create an App with a Database in which I will add several collections in Cloud Firestore.
but it is impossible, since the app was broken when I added the code to connect the app.
I've seen various solutions on Stack and GitHub, but after hours of testing, it doesn't work.
bud search
Firebase v9 modular - Can't find variable: IDBIndex
https://github.com/expo/expo/issues/8089
For now the Application is very simple, only two files are involved in Firebase and nothing works
I have changed the way to call Firebase in several ways:
import firebase from 'firebase/app'
import 'firebase/firestore'
import {initializeApp} from 'firebase/app'
import 'firebase/firestore'
import firebase from 'firebase/compat/app'
import 'firebase/compat/firestore'
Currently the code I have is the following:
import firebase from 'firebase/app'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxx",
appId: "xxxxxxxxxxx"
}
export const firebaseApp = firebase.initializeApp(firebaseConfig)
file actions.js
import { firebaseApp } from "./firebase"
import firebase from 'firebase/app'
import 'firebase/firestore'
const db = firebase.firestore(firebaseApp)
export const isUserLogged = () => {
let isLogged = false
firebase.auth().onAuthStateChanged((user)=> {
user !== null && (isLogged = true)
})
return isLogged
}
And the errors that the console shows me:
**
TypeError: undefined is not an object (evaluating '_app.default.initializeApp')
- ... 9 more stack frames from framework internals
Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:6 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError
at node_modules/#react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError
**
How can I correct this error?
You're importing functions from the newer modular SDK, but then are tryign to call the older namespaced APIs. That won't work.
I recommend using the code samples from getting started with Firebase Authentication on the web, getting the currently signed in user and the upgrade guide.
With the new modular syntax, you can build a function that returns a promise with first auth state with:
import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth";
const firebaseConfig = {
// ...
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export const isUserLogged = () => {
return new Promise((resolve, reject) => {
let unsubcribe = onAuthStateChanged(auth, (user) => {
unsubcribe();
resolve(user !== null)
})
});
}
If you want to stick to using the namespaced API, you can either import an older version of Firebase (e.g. the latest v8 release) or use the compat path for the new SDK, in the same upgrade guide I linked above.

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

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 }
}
}

Server Error TypeError: Cannot read properties of undefined (reading 'apps')

this is my firebase sdk version
firebase#9.0.2
this is init code of firebase i cant solve this please help me for this error
export default function initFirebase() {
if(!firebase.apps.length){
firebase.initializeApp(clientCredentials)
if(typeof window !=='undefined'){
if('measurementId' in clientCredentials){
firebase.analytics()
firebase.performance()
}
}
console.log('firebase was successfully init')
}
}
How i import firebase
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/storage'
import 'firebase/analytics'
import 'firebase/performance'
You are using the new Modular SDK (V9.0.0+) which is designed to facilitate tree-shaking (removal of unused code) to make your web app as small and fast as possible. If you want to use your existing code (V8 name-spaced syntax) then you would have to change your imports to compat versions as shown below:
import firebase from 'firebase/compat/app'
import 'firebase/compat/firestore'
// import 'firebase/compat/[SERVICE_NAME]'
However, I would recommend upgrading to the new SDK. The modular/functional syntax looks like this:
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore'
const app = initializeApp({ ...firebaseConfig })
const auth = getAuth(app)
const firestore = getFirestore(app)
// other Firebase services
You don't have to check if a default Firebase app instance already exists in the modular syntax. However, if you need to list Firebase instances, you can do so using getApps():
import { getApps } from 'firebase/app'
console.log(getApps())
Below is what worked for me, the issue started after I upgraded to Firebase 9
import firebase from 'firebase/compat/app';
import * as firebaseui from 'firebaseui'
import 'firebaseui/dist/firebaseui.css'
My firebase initialization looks like below:
let ui = firebaseui.auth.AuthUI.getInstance()
if (!ui) {
ui = new firebaseui.auth.AuthUI(firebase.auth())
}
ui.start('#firebaseui-auth-container', {
signInFlow: isDesktop() ? 'popup' : 'redirect',
callbacks: {
signInSuccessWithAuthResult() {
window.location.assign(`/home`)
// firebase.auth().signOut()
return false
},
},
...
You can't use the Firebase Auth UI library with the modular SDK yet. Check this for more details.

'No Firebase App '[DEFAULT]' has been created' even though initializeApp is called

I am trying to add Firebase (Firestore) to my Nuxt project, however I am recieving the following error when initialising a const from firebase.firestore() in my index.vue file:
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been
created - call Firebase App.initializeApp() (app/no-app).
I have installed Firebase in my project and also the module (#nuxtjs/firebase).
My nuxt.config.js file looks like this:
export default {
...
plugins: ['~/plugins/firebase.js'],
components: true,
buildModules: [
'#nuxt/typescript-build',
'#nuxtjs/tailwindcss',
],
modules: [],
...
}
And my firebase.js file is within my plugins folder as follows:
import firebase from 'firebase/app'
const config = {
...
}
let app = null
if (!firebase.apps.length) {
app = firebase.initializeApp(config)
}
export default firebase
I've compared the above to other examples online and haven't spotted any issues. However I'm new to everything from Nuxt to Firebase, so I may be missing something obvious. Any suggestions appreciated.
This typically happens if you call initializeApp() more than once on a single firebase app. If you're working with a single firebase db, make sure to initialize it when your app starts.
According to this GitHub Discussion this snippet for firebase.js should work:
import fb from "firebase/app"
export const firebase = !fb.apps.length ? fb.initializeApp(firebaseConfig) : fb.app()
// somecomponent.js
import {firebase} from "../firebase.js"
// do your firebase stuff here
Credit to #Brunocrosier with his post; even though this snippet isn't case-specific, I decided to include it for the sake of completeness.
Besides this thread - generally speaking, Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app). is often a result of of either calling firebase. before initializing via .initializeApp(); or by calling .initializeApp() multiple times (for example Next.js might try to initialize it on the back- as well as the frontend - which seems to be the case in your code) within your firebase app.
Hence as a solution I highly suggest to move your initialization to the firebase.js file in order to initialize it directly when your app starts.
For further reading purposes:
The nuxt/firebase documentation
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()
The previously mentioned GitHub Discussion
FireBase JavaScript documentation
This normally happens when you try to access firestore before initializing the firebase. So as default we can check if firebase is initialized or not by firebase.apps.length but it's not a good practice to initialize firebase each and every time.
so if you are only using firestore then in your plugin you can export firestore directly after initialization like following,
import firebase from 'firebase/app'
const config = {
...
}
let app = null
if (!firebase.apps.length) {
app = firebase.initializeApp(config)
}
export default firebase.firestore()
But since you are working with nuxt there is special nuxt package called firebase/nuxt
with that installed you can define your configuration in nuxt config inside the module section as bellow,
modules: [
[
'#nuxtjs/firebase',
{
config: {
apiKey: '<apiKey>',
authDomain: '<authDomain>',
databaseURL: '<databaseURL>',
projectId: '<projectId>',
storageBucket: '<storageBucket>',
messagingSenderId: '<messagingSenderId>',
appId: '<appId>',
measurementId: '<measurementId>'
},
services: {
auth: true // Just as example. Can be any other service.
}
}
]
],
I think it is a better way to use firebase inside the nuxt.js

Categories

Resources