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

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.

Related

Unable to Initialize firebase in Vue web app

I am trying to use a Cloud Firestore database collection in my vue app. However, when I run npm run serve to load my vue app in the browser, I am met with an error:
This relative module was not found:
* ./firebaseInit in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=js&
I've made sure to install npm install firebase --save, but I am still getting the above error.
I have a two files that setup firebase in my root directory, firebaseConfig.js that holds my app settings and firebaseInit.js that imports and exports firebase throughout my app. Below is a screenshot of my directory structure.
// firebaseConfig.js
export default {
//mock data
apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",
authDomain: "myapp-project-123.firebaseapp.com",
databaseURL: "https://myapp-project-123.firebaseio.com",
projectId: "myapp-project-123",
storageBucket: "myapp-project-123.appspot.com",
messagingSenderId: "65211879809",
appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",
}
// firebaseInit.js
import firebase from 'firebase/app'
import 'firebase/firestore'
import firebaseConfig from './firebaseConfig'
const firebaseApp = firebase.initializeApp(firebaseConfig)
export default firebaseApp.firestore()
When I try and import firebaseInit.js in my app.js file, I am met with the error stated above.
// App.vue
... <template>
<script>
import db from './firebaseInit'
</script>
I've tried looking into the docs and registering the config files in App.vue, but that did not work.
Add this to
firebaseInit.js
export default const db = firebaseApp.firestore();
I had a similar problem. I also consolidated the 2 files into one file called firebaseApp.js which looks like this
import firebase from 'firebase'
import 'firebase/firestore'
var firebaseConfig = {
apiKey: "AIzaSyDoAX0RM_eB_Zv7_P3ENJZOe97jaN5-JNE",
authDomain: "vuefs-prod-trav.firebaseapp.com",
projectId: "vuefs-prod-trav",
storageBucket: "vuefs-prod-trav.appspot.com",
messagingSenderId: "378644247244",
appId: "1:378644247244:web:1a06b2e6c30c5ac2e54869",
measurementId: "G-ZVGYPK8YRX"
}
firebase.initializeApp(firebaseConfig)
var db = firebase.firestore()
export default db
Finally, import it as:
import db from './firebaseApp' inside your <script> of example.vue file.
Hope this helps you!!
As mentioned by #Phil in the comments you could either import the script by using
import db from "../firebaseInit.js"
with the ../ indicating that your are importing from a top level directory, or you could place the scripts in the same src folder and keep the import as is.

Using with Firebase / Expo query to Cloud Firestore

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

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

Error with initialization of firebase while running Vue-CLI app

I'm pretty new to Vue-CLI and Firebase. I've been using Firebase for authorization and Firestore DB. I Have Encountered the following error while trying to render my application in browser:
Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_3_firebase___default.a.auth is not a function
From what I've looked, it seems like there's something wrong with how I am initializing Firebase, but I couldn't find the problem.
Here is my main.js file:
import Vue from 'vue'
import App from './App'
import router from './router'
import firebase from 'firebase'
import 'firebase/firestore'
Vue.config.productionTip = false
let app
let fireBaseConfig = {
apiKey: ***,
authDomain: ***,
databaseURL: ***,
projectId: ***,
storageBucket: ***,
messagingSenderId: ***
};
firebase.initializeApp(fireBaseConfig)
firebase.auth().onAuthStateChanged(function(user){
if(!app){
/* eslint-disable no-new */
app = new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
}
});
const firestore = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
export { firestore }

Vue.Js - Firebase functions cannot be used on components

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

Resources