I want to enable offline data in my project.
I found the right code for this but I don't know where to implement the code
I implement the code inside the firebaseConfig.js file:
import firebase from 'firebase'
import 'firebase/firestore'
// firebase init
// init code goes here
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
}
firebase.initializeApp(config)
firebase.firestore().enablePersistence()
.then(function () {
// Initialize Cloud Firestore through firebase
var db = firebase.firestore();
})
.catch(function (err) {
console.log(err)
})
// firebase utils
const db = firebase.firestore()
const oldRealTimeDb = firebase.database()
const auth = firebase.auth()
const currentUser = auth.currentUser
// date issue fix according to firebase
const settings = {
timestampsInSnapshots: true
}
db.settings(settings)
// firebase collections
const usersCollection = db.collection('users')
const postsCollection = db.collection('posts')
export {
db,
auth,
currentUser,
postsCollection,
usersCollection
}
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store'
import './registerServiceWorker'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css' // Ensure you are using css-loader
const fb = require('./firebaseConfig.js')
Vue.config.productionTip = false
export const bus = new Vue()
Vue.use(Vuetify)
let app
fb.auth.onAuthStateChanged(user => {
if (!app) {
app = new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: {
App
},
render: h => h(App)
}).$mount('#app')
}
})
I got this error:
The sample code provided in the documentation suggests that you should call enablePersistence() and possibly make note if it fails for some given reason:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});
firebase.firestore().enablePersistence()
.catch(function(err) {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
// ...
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
Subsequent queries after calling enablePersistence() will be internally queued until it fully completes, which means that the query may or may not be using locally cached data, depending on the result of enablePersistence(). If it's important to your app to be able to use local persistence, you may wish to wait on its result (triggering on the returned promise) before performing the query.
Just remove the second firebase.firestore() and call the enablePersistence as follows:
import firebase from 'firebase'
import 'firebase/firestore'
// firebase init
// init code goes here
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
}
firebase.initializeApp(config)
const db = firebase.firestore();
const auth = firebase.auth();
const currentUser = auth.currentUser;
// date issue fix according to firebase
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
db.enablePersistence();
// firebase utils
//const db = firebase.firestore() // <---- Remove this line
const oldRealTimeDb = firebase.database()
const auth = firebase.auth()
const currentUser = auth.currentUser
Related
Randomizing content may be a useful functionality for different applications. The following code completes the task for a firebase firestore collection.
Sample firebase initialization main shuffle code below
// Import Firebase
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { doc, getDoc, getDocs, collection, getFirestore } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-firestore.js";
// Firebase Config
const firebaseConfig = {
apiKey: "your-info",
authDomain: "your-info",
databaseURL: "your-info",
projectId: "your-info",
storageBucket: "your-info",
messagingSenderId: "your-info",
appId: "your-info",
measurementId: "your-info"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firestore
const firestore = getFirestore(app);
Code to get a sample 'contributions' collection and console log shuffled docs:
// Get Collection
const contributionsCollection = collection(firestore, 'contributions');
// Get Collection Docs
const contributionsCollectionDoc = await getDocs(contributionsCollection);
// Fill in Contributions
if(contributionsCollectionDoc.empty == false) {
var contributions = contributionsCollectionDoc.docs;
shuffle(contributions);
contributions((doc) => {
console.log(doc.data());
});
}
I'm new to react-native and JS. My project is a chat app and I'm trying to create button that onPress creating new chat, using the following function:
const createChat = async () =>{
await db
.collection("chats")
.add({
chatName: input,
})
.then(() => {
navigation.goBack();
})
.catch((error) => alert(error));
}
this my firebase.js file:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/database';
const firebaseConfig = {
apiKey: "*",
authDomain: "*",
projectId: "*",
storageBucket: "*",
messagingSenderId: "*",
appId: "*",
measurementId: "*"
};
let app;
if (firebase.apps.length === 0){
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app();
}
const db = firebase.app();
const auth = firebase.auth();
export {db , auth};
const db = firebase.app(); // an instance of FirebaseApp
should be
const db = firebase.firestore(); // an instance of Firestore
Instead of learning using the compatibility library, consider learning the new Modular SDK instead as this will be the way forward.
I'm very new to next.js, and I'm developing an API with it, side that API I want to use firebase, so I set up firebase but when I try to call it, this error appears: "unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization"
Code below.
Firebase config file
import firebase from 'firebase/app';
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "*******",
authDomain: "********",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
//if(!firebase.apps.length){
//}
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
Firestore service
import { firestore } from './firebase';
export class Firestore {
async getOne(collection, uid){
const data = await firestore.collection(`${collection}/${uid}`).get();
return await data.docs();
}
}
API page
import {Firestore} from '../../utils/firestore';
const firestore = new Firestore();
const getBanners = () => {
return firestore.getOne('settings','client');
//return data;
}
export default function Handler(req,res){
res.status(200).json({
'name':"getBanners",
'data': getBanners()
});
}
I solved this issue by adding import firebase from 'firebase/compat/app'; and also import 'firebase/compat/firestore';. And works!
I am using firebase google authentication to authenticate user using goole.
But i am facing an error which is given below....
(0, _auth.signInWithPopup) is not a function. (In '(0, _auth.signInWithPopup)(auth, provider)', '(0, _auth.signInWithPopup)' is
undefined)
and unable to fix it.
here is my code ...
import statements
import {getAuth,GoogleAuthProvider,signInWithPopup} from "firebase/auth"
the function
const googlelogin=async()=>{
const auth=getAuth()
const provider=new GoogleAuthProvider()
try{
const result=await signInWithPopup(auth,provider)
// const credentials=GoogleAuthProvider.credentialFromResult(result);
// const token=credentials.accessToken
// const user=result.user
}
catch(e){
console.log(e)
}
}
Please tell me how to solve this error...
Thanks in advance
getAuth() function can not be empty. first you should pass the firebase configurations which are can be found on firebase app -> project settings to the initializeApp() function. then pass the results to the getAuth() function.
import {initializeApp} from "firebase/app";
import {getAuth} from 'firebase/auth';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp);
I'm trying to add authentication using Firebase in my Vue app, but I'm getting [Vue warn]: Error in v-on handler: "TypeError: _config_firebase__WEBPACK_IMPORTED_MODULE_8__.user.SignInWithEmailAndPassword is not a function" error.
Here is my irebase config file:
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_AUTH_DOMAIN",
databaseURL: "MY_DB_URL",
projectId: "MY_PROJECT_ID",
storageBucket: "MY_STORAGE_BUCKET",
messagingSenderId: "MY_MESSAGE_SENDER_ID",
appId: "MY_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a Firestore instance
export const user = firebase.auth();
export const db = firebase.firestore();
Then the action in Vuex:
import { db, user } from "./config/firebase";
loginUser({ commit }, payload) {
user
.SignInWithEmailAndPassword(payload)
.then(user => {
console.log(user);
commit("SET_USER", user);
})
.catch(error => {
commit("setLoading", false);
commit("setError", error);
console.log(error);
});
router.push("/");
}
So far, I have been able to Create, Read, Update and Delete, although, the config file was slightly different than this, when I added auth was when I altered the code.
Change this:
user.SignInWithEmailAndPassword(payload)
into this:
user.signInWithEmailAndPassword(payload)
From the docs:
Asynchronously signs in using an email and password.