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());
});
}
Related
below is my javascript code snippet, it responds showing all admin databases,taufik,nanarsih,,,I want to get the database value with admin key, how do I do that?
<script type="module">
// Import the functions you need from the SDKs you need
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.6.11/firebase-app.js";
import {
getAnalytics
} from "https://www.gstatic.com/firebasejs/9.6.11/firebase-analytics.js";
import {
getDatabase,
ref,
onValue,
equalTo
} from "https://cdnjs.cloudflare.com/ajax/libs/firebase/9.6.11/firebase-database.min.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "123",
authDomain: "123",
databaseURL: "123",
projectId: "123",
storageBucket: "123",
messagingSenderId: "123",
appId: "123",
measurementId: "123"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getDatabase(app);
onValue(ref(db), (snapshot) => {
const data = snapshot.val();
console.log(data);
});
this is the response in the console log:
{admin: 123, nanarsih: 123, taufik: 123}
To just get the admin vaue from the database, you can create a reference to that path and then read that:
const adminRef = ref(db, 'admin');
onValue(adminRef, (snapshot) => {
const data = snapshot.val();
console.log(data);
});
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!
Just trying to set it up firebase for the first time and I get these errors cant find any right answer to work this is my config
// Import the functions you need from the SDKs you need
import firebase from 'firebase/compat/app';
import 'firebase/firestore';
import {
initializeApp
}
from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "x",
authDomain: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x",
appId: "x"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = firebase.firestore();
export {
db
};
the error I get -
TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.firestore is not a function
it shows to the line
const db = firebase.firestore();
If you want to use the compat version of firestore you need to initialize the firebaseApp also with the compat version. I would recommend using the new SDK version for both:
import { getFirestore } from "firebase/firestore";
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "x",
authDomain: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x",
appId: "x",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
export { db };
With the new SDK, you actually don't need such a file like before where you initialize your app and create the database instances. After you initialize your app with the new SDK you can just call getFirestore() without the need to have the firebaseApp for it. getFirestore() will automatically use the default app.
A realtime listener by using collection would look like this:
import { collection, onSnapshot } from "firebase/firestore";
const unsubscribe = onSnapshot(collection(db, "cities"), () => {
// Respond to data
// ...
});
// Later ...
// Stop listening to changes
unsubscribe();
When you read the Firebase docs make sure to switch to the SDK 9 version:
Try replacing this line of your code:
import 'firebase/firestore';
for this:
import 'firebase/compat/firestore';
This way you'll be using compatability api in both imports
I am doing a small project with Google authentication. Now, this is my first time doing this, so I might be doing something wrong which I am not seeing. I did the following steps:
-I went on firebase and linked my account
-I enabled google to be able to use it for authentication
-I pasted the project data in my file, as I will show in a bit
-and I put the code for the autentication
<script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyArVSWB1OYZYQJEkmc6uIi9jyfmRIW1oSk",
authDomain: "assignment-da42d.firebaseapp.com",
databaseURL: "https://assignment-da42d.firebaseio.com",
projectId: "assignment-da42d",
storageBucket: "assignment-da42d.appspot.com",
messagingSenderId: "569189156463",
appId: "",
measurementId: "G-N6D1788RXF"
};
firebase.initializeApp(firebaseConfig);
function googleSignIn(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider)
}
</script>
<button onclick="googleSignIn()">Google Sign in</button>
However, even after following multiple tutorials, using the same methods, I kept getting the error:
Uncaught TypeError: Cannot read property 'GoogleAuthProvider' of undefined
What am I doing wrong please?
I had the same issues late week and I've since solved it.
Can you point out where you include the following or some other version of the auth library?
<script src="/__/firebase/[version number]/firebase-auth.js"></script>
If that's missing you can paste it in before your code.
I installed the whole package - $ npm install --save firebase
and my config file looks like
import firebase from "firebase/app";
import "firebase/storage";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "......",
authDomain: ".....",
databaseURL: ".....",
projectId: ".....",
storageBucket: ".....",
messagingSenderId: "......",
appId: "......",
measurementId: "...."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const projectStorage = firebase.storage();
export const projectFirestore = firebase.firestore();
export const timestamp = firebase.firestore.FieldValue.serverTimestamp;
export const auth = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () =>{
auth.signInWithRedirect(provider).then(function(){
});
};
and I can call
const logIn = () => {
let ret = signInWithGoogle();
console.log(ret);
getCredentials();
}
in the navbar.
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