Vue.Js - Firebase functions cannot be used on components - firebase

I was using Vue Resource in posting data from my web app to the firebase. but then, I just found out that I need to use firebase integration to upload IMAGES in the firebase storage. so I integrated it in my src/main.js
import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import * as firebase from 'firebase'
import App from './App.vue'
import Routes from './routes'
Vue.use(VueResource);
Vue.use(VueRouter);
const router = new VueRouter({
routes: Routes,
mode: 'history'
});
new Vue({
el: '#app',
render: h => h(App),
router: router,
created () {
firebase.initializeApp({
apiKey: 'AIzaSyDhdEhcLPfGqo5_msnhVKWH9BkZNOc6RYw',
authDomain: 'nots-76611.firebaseapp.com',
databaseURL: 'https://nots-76611.firebaseio.com',
projectId: 'nots-76611',
storageBucket: 'gs://nots-76611.appspot.com'
})
}
})
but when I tried to use it in one of my components' methods:
methods: {
post: function(){
//for(var i = 0; i < this.tailors.length; i++){
// if(this.$route.params.id == this.tailors[i].id)
// this.ready_to_wear.tailor_name = this.tailors[i].tName;
//}
//this.$http.post('https://nots-76611.firebaseio.com/ready_to_wear.json', this.ready_to_wear);
let key
firebase.database().ref('ready_to_wears').push(this.ready_to_wear)
.then((data) => {
key = data.key
return key
})
.then(key => {
const filename = this.image.name
const ext = filename.slice(filename.lastIndexOf('.'))
return firebase.storage().ref('rtws/' + key + '.' + ext).put(this.image)
})
.then(fileData => {
imageUrl = fileData.metadata.downloadURLs[0]
return firebase.database().ref('ready_to_wears').child(key).update({rtwImg: imageUrl})
});
}
}
.. it says in the console log that 'firebase' is not defined
I'm guessing that firebase functions can't be used in the components even though it is integrated in the main.js
How do I make use of it in the components? is there any other way around it?

You don't appear to be using VueFire, which I believe exposes firebase through a Vue prototype property as $firebase. However, you can do it yourself manually.
import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import * as firebase from 'firebase'
import App from './App.vue'
import Routes from './routes'
Vue.prototype.$firebase = firebase
After that, firebase will be available in every Vue or component as this.$firebase.
methods: {
post: function(){
this.$firebase.database().ref() ... etc ...
}
}

Related

how to access Vuex store from Axios config file?

I'm using Vue 3 composition and Vuex
this is axios config file
http.js
import axios from "axios";
import useStore from "#/stores/index.js";
const store = useStore()
const http = axios.create({
//from env
baseURL: "https://challenge.spexa.dev/"
})
http.interceptors.request.use(function (config) {
console.log("store" + store) // return undefined
const token = store.getters['token']
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
});
export default http
the problem is that store works fine inside component But not in axios config module and I cant access it (!!!?) .
and this is store
store/index.js
import Vuex from "vuex";
import http from "../services/http";
export default new Vuex.Store({
state: {
access_token: null,
refresh_token: null,
},
getters: {
token(state) {
return state.access_token
}
},
});
and this is main.js
import { createApp } from 'vue'
import store from './stores/index';
import App from './App.vue'
createApp(App).use(store).mount('#app')
so ,what's the problem ?
so ,what's the problem ?
well, hard to tell without seeing what useStore from "#/stores/index.js" is doing.
store works fine inside component But not in axios config module
Is not a lot to go one and you may need to define what "not" working means. Is sotre undefined or is the value not staying reactive?
Maybe you meant to do this 🤷‍♂️:
import { store } from "#/stores/index.js";
instead of"
import useStore from "#/stores/index.js";
const store = useStore()

Firebase analytics are not supported in this enviroment [duplicate]

I have a react/nextjs app and I have firebase.js as follow:
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/analytics'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: '...'
}
try {
firebase.initializeApp(firebaseConfig)
firebase.analytics()
} catch (err) {
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
export default firebase
I kept getting
Firebase initialization error ReferenceError: navigator is not defined
after adding analytics to the firebase.js file. What is the correct way to add analytics to the app?
import { getAnalytics, isSupported } from "firebase/analytics";
const analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);
Try this one
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/firestore"
import "firebase/storage"
import "firebase/analytics"
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
// Auth export
export const auth = firebase.auth()
// Firestore exports
export const firestore = firebase.firestore()
export const serverTimestamp = firebase.firestore.FieldValue.serverTimestamp
export const fbTimestamp = firebase.firestore.Timestamp
export const fromMillis = firebase.firestore.Timestamp.fromMillis
export const increment = firebase.firestore.FieldValue.increment
// Storage exports
export const storage = firebase.storage()
export const analytics = () => {
if (typeof window !== "undefined") {
return firebase.analytics()
} else {
return null
}
}
export default firebase
ReferenceError: navigator is not defined
because there is no window object present during the server-side rendering of the Nextjs application.
Try:
if(typeof window != undefined){
firebase.analytics()
}
I just updated my firebase to version 9 and this error is not seen.
Update to version 9 could be a solution to this.
But for version 9, there are some changes in firebase declaration.
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
Using firebase V 9.16 this how I solved the issue
import { initializeApp } from "firebase/app";
import { getAnalytics, isSupported } from "firebase/analytics";
import { getFirestore } from "firebase/firestore"
const firebaseConfig = {
...
};
let app; let analytics; let db
if(typeof window != undefined){
app = initializeApp(firebaseConfig);
analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);
db = getFirestore(app)
}
export {app, analytics, db}
In _app.js I import analytics and i use useEffect like
useEffect(() => {
analytics;
}, [])

unresolved variable $firebaseRefs vue js

I have an add function to add movies to firebase database
methods: {
add() {
this.$firebaseRefs.movies.push({
name: this.newItem.name,
price: this.newItem.genre,
rating: this.newItem.rating,
reviews: this.newItem.reviews,
cast: this.newItem.cast,
});
this.newItem.name = '';
this.newItem.genre = '';
this.newItem.rating = '';
this.newItem.reviews= '';
this.newItem.cast= '';
this.$router.push('/dashboard')
}
}
}
But am getting an error Unresolved variable $firebaseRefs and when I try to add the route changes to
http://localhost:8080/add?
I have imported that
import { db } from '../db';
db.js
import * as firebase from "firebase";
import store from "./store";
let config={
apiKey: "AIzaSyDQ2dXBMuIJ2EBYeVqucJpOF33C0tsFlLk",
authDomain: "tv-show-tracker-9899e.firebaseapp.com",
databaseURL: "https://tv-show-tracker-9899e.firebaseio.com",
projectId: "tv-show-tracker-9899e",
storageBucket: "tv-show-tracker-9899e.appspot.com",
messagingSenderId: "433917891798",
appId: "1:433917891798:web:bb35a74ae42e6db339a577"
};
let app = firebase.initializeApp(config);
export const db = app.database();
// eslint-disable-next-line no-unused-vars
let firebaseRefs = db.ref('movies');
firebase.auth().onAuthStateChanged(user => {
store.dispatch("fetchUser", user);
});
Below is the main.js file
main.js
import Vue from 'vue'
import App from './App.vue'
import router from "./routes/route.js";
import store from "./store";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
As explained in the vuefire documentation, you need to install Vuefire as a Vue plugin. Therefore, since you use the Realtime Database, you need to adapt your main.js file as follows
import Vue from 'vue'
import App from './App.vue'
import router from "./routes/route.js";
import store from "./store";
import { rtdbPlugin } from 'vuefire'
Vue.use(rtdbPlugin)
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
Do not forget to install the latest version of Vuefire as follows (see doc):
npm install vuefire

(Webpack failing to build?) Firebase DB in different levels of Vue components

I'm trying to set up a vue-fire app using single file Vue components.
I'm using the standard (full) Vue-cli Webpack template available on the official site.
I have firebase loaded in App.vue like this:
let config = {
...
};
let app = Firebase.initializeApp(config);
let db = app.database();
let usersRef = db.ref('users');
...
export default {
name: 'app',
data () {
return {
login: {
email: '',
password: ''
},
newUser: {
email: '',
password: ''
},
showRegister: false
}
},
firebase: {
users: usersRef,
},
...
}
I'm using Vue-router and my routes are set up like this:
import Vue from 'vue'
import Router from 'vue-router'
import Home from '#/components/Home'
import News from '#/components/News'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/news',
name: 'News',
component: News
}
]
})
I would like to be able to access my Firebase app in the 'News' component. The problem is that if I include the entire Firbase setup in the News.vue file, I get the error:
[DEFAULT]: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
The recommended solution is to export the initialized app's database in App.vue and import it in the child component. So I add this to the bottom of my App.vue script:
module.exports.FBApp = app.database();
And this to News.vue:
import FBApp from '../App.vue'
let usersRef = FBApp.ref('users')
But now I am getting the following error:
TypeError: __WEBPACK_IMPORTED_MODULE_0__App_vue___default.a.ref is not a function
Does anyone know how to do this? Surely it can't be too hard.
Create a db.js file like the following alongside app.vue.
import firebase from 'firebase'
var config = {
apiKey: 'xxxxx'
authDomain: 'xxxxx'
databaseURL: 'xxxxx'
projectId: 'xxxxx'
storageBucket: 'xxxxx'
messagingSenderId: 'xxxxx'
}
const firebaseApp = firebase.initializeApp(config)
const db = firebaseApp.database()
export default db
In your main.js:
import Vue from 'vue'
import App from './App'
import router from './router'
import VueFire from 'vuefire'
// explicit installation required in module environments
Vue.use(VueFire)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
And now in any component, eg:
<template>
<span>
{{ news }}
</span>
</template>
<script>
import db from '../db'
export default {
data: function () {
return {
users: [],
sample: []
}
},
firebase: function () {
return {
news: db.ref('news')
}
}
}
</script>

Using firebase in vuejs2 app via vue-cli(webpack)

I am new to using vue-cli a webpack template
I want to use firebase as my database for the vueapp
i have done this to import Firebase into my app
main.js
//imported rest all required packages just dint mention here
import * as firebase from 'firebase'
let config = {
apiKey: " - XXXXXXXXCXCC",
authDomain: "XXXXXXXXX",
databaseURL: "XXXXXCCCX",
storageBucket: "XXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXX"
};
firebase.initializeApp(config);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
Now in my signup.vue file i have to import the following again
import * as firebase from 'firebase'
In order to use the following in my methods
firebase.auth().createUserWithEmailAndPassword(uEmail, uPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
My question is do i have to import
import * as firebase from 'firebase'
everywhere (i.e in alll vue components script tags to use firebase related methods like
firebase.auth()
firebase.database()
firebase.storage()
or can i import it at one central place and use firebase.method() in any vue component file when needed
You could attach the firebase to the Vue.prototype:
import * as firebase from 'firebase'
let config = {
//
}
Vue.prototype.$firebase = firebase.initializeApp(config)
new Vue({
//
})
Then, use it to the components like this:
this.$firebase.database()
If you want to import it just once, you can simply do in your main.js:
import * as firebase from 'firebase'
window.firebase = firebase
window object is global for webpage and it's normal practice to use it this way.

Resources