Firebase .on with Vue without using Vuefire - firebase

I'm trying to implement a real-time connection with Firebase's .on ref, but have no idea where to plug that in or use it in Vue. The tutorials online all use Vuefire to accomplish it, but if I just want to use the Firebase SDK, where can I activate this .on connection in my Vue project and have it work in a two-way data connection real-time?
Hmm.. It didn't seem to work.
This is what I'm using,
export default {
name: 'index',
data() {
return {
id: '1234',
meData: 'test'
}
},
mounted() {
const database = firebase.database().ref( 'rooms' + this.id );
database.on( 'value', snapshot => {
this.meData = snapshot.val();
});
}
}
I tried testing with push, it works, so the config and firebase is working, but the .on doesn't seem to work. I get no errors too so I'm having a hard time figuring out the issue. =(

At first, always the best option is to use VueFire if you need to use Vue.js and Firebase.
However, if you want to use Vue.js without Vuefire, you can set up the firebase instance in mounted section in your component. Vue component's lifecycle is not the same as the one without Vue, so you better to use lifecycle handler provided by Vue.
Vue.component("YourComponent", {
...
mounted() {
firebase.initializeApp({
apiKey: "apiKey",,
databaseURL: "https://databaseName.firebaseio.com"
});
const database = firebase.database();
database.ref('/users/100').once('value').then((snapshot) => {
// Do your business
});
...
//
// You can also set up more handlers like above...
//
},
...
});
However, if you want to use two-way binding, it is a little tough. The good point of Vuefire is its easy mixin of Vue component data structure and Firebase instance.
Without Vuefire, the code I can think up would be like this
Vue.component("YourComponent", {
...
data() {
return {
users: []
};
},
...
mounted() {
//
// Initialize Firebase SDK and get `database` to use below.
//
...
database.ref('/users').on('value', (snapshot) => {
// By using arrow function, the context of `this` here is binded
// into the current component data `users`.
this.users = snapshot.val();
});
},
...
});

In case anyone else is looking to use Firebase in Vue without Vuefire.
Do check out this video!
Vue 2 & Vuex & Firebase Tutorial - Getting It All Working Together
https://youtu.be/niPgyv53x8c

Related

Next.js with Firebase Remote Config

I was trying to integrate Google's Firebase Remote config into my Next.js app.
When following Firebase's docs, and just inserted the functions directly into my component's code block, like so:
const remoteConfig = getRemoteConfig(app);
I keep getting the following error when following their documentation:
FirebaseError: Remote Config: Undefined window object. This SDK only supports usage in a browser environment.
I understand that it happens since Nextjs is rendered server-side, so there's no window object yet, so here's my solution:
import {
fetchAndActivate,
getRemoteConfig,
getString,
} from 'firebase/remote-config';
const Home: NextPage<Props> = (props) => {
const [title, setTitle] = useState<string | null>('Is It True?');
useEffect(() => {
if (typeof window !== 'undefined') {
const remoteConfig = getRemoteConfig(app);
remoteConfig.settings.minimumFetchIntervalMillis = 3600000;
fetchAndActivate(remoteConfig)
.then(() => {
const titleData = getString(remoteConfig, 'trueOrFalse');
setTitle(titleData);
})
.catch((err) => {
console.log(err);
});
}
});
return <h1>{title}</h1>}
Basically, the important part is the if statement that checks if the window object exists, then it execute the Remote Config functions according to Firebase documents.
Also, it worked outside a useEffect, but I think that's probably a bad idea to leave it outside, maybe even it should have a dependency, can't think of one at the moment.

Getstream firebase auth react native documentation?

Not sure if anyone has any experience with getstream and react native.
I followed there tutorial to implement getstreams SDK into my existing app and its working great but I'm stuck on tokens. I've successfully set up firebase so when a new user signs up I can see there UID and information over on both firebase auth and getstream but I'm hung up on my frontend getting the user to sign in on the chat with there token. I set up firebase with there extension but still having issues. Works great with dev.tokens but just can't get past this part. Is there any examples out there or better documentation for this? Thank you!
Only documentation I can find.. not specific to react native
https://getstream.io/chat/docs/react/tokens_and_authentication/
This is currently how I initialize my user.. the user token is hard coded in my chat config file.
// useChatClient.js
import { useEffect, useState } from 'react';
import { StreamChat } from 'stream-chat';
import { chatApiKey, chatUserId, chatUserName, chatUserToken } from './chatConfig';
const user = {
id: chatUserId,
name: chatUserName,
};
const chatClient = StreamChat.getInstance(chatApiKey);
export const useChatClient = () => {
const [clientIsReady, setClientIsReady] = useState(false);
useEffect(() => {
const setupClient = async () => {
try {
chatClient.connectUser(user, chatUserToken);
setClientIsReady(true);
// connectUser is an async function. So you can choose to await for it or not depending on your use case (e.g. to show custom loading indicator)
// But in case you need the chat to load from offline storage first then you should render chat components
// immediately after calling `connectUser()`.
// BUT ITS NECESSARY TO CALL connectUser FIRST IN ANY CASE.
} catch (error) {
if (error instanceof Error) {
console.error(`An error occurred while connecting the user: ${error.message}`);
}
}
};
// If the chat client has a value in the field `userID`, a user is already connected
// and we can skip trying to connect the user again.
if (!chatClient.userID) {
setupClient();
}
}, []);
return {
clientIsReady,
};
};
The next step is to request the token from the Firebase cloud function (ext-auth-chat-getStreamUserToken), and then initialise the current user with that token.
There is a guide and video showing how to do this using the Stream Chat Flutter SDK:
https://getstream.io/chat/docs/sdk/flutter/guides/token_generation_with_firebase/
https://youtu.be/Dt_taxX98sg

Firebase sdk with react native unable to see anything

I am following this tutorial on RN with Firestore. I've so far only used the Firebase Web SDK installed via
npm install firebase -save
With the following example code:
constructor(props) {
super(props);
this.ref = firebase.firestore().collection('sessions');
this.unsubscribe = null;
this.state = {
dataSource: [],
loading: true,
};
}
componentDidMount() {
this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
}
componentWillUnmount() {
his.unsubscribe();
}
onCollectionUpdate = (querySnapshot) => {
const dataSource = [];
querySnapshot.forEach((doc) => {
const { id, desc, zipcode, timestamp } = doc.data();
dataSource.push({
key: doc.id,
doc,
desc,
zipcode,
timestamp,
});
});
this.setState({
dataSource,
loading: false,
});
}
The above code returns absolutely nothing, even if I put a bogus collection name. Nothing runs, and I put a bunch of console.log statements but still can't see anything. I can't even tell if there is any problems connecting to Firestore.
I have not yet tried react-native-firebase module because I thought I am only doing a simple Firestore query, but at same time I am building my app natively on iOS on a Mac.
Am I supposed to be using the react-native-firebase module?
There is a typo error in your componentWillMount. componentWillUnmount() {
his.unsubscribe();
}
should be: componentWillUnmount() {
this.unsubscribe();
}
Also i recommend react-native-firebase.
So for anyone who found this with similar issues, just want to confirm that the Firebase Web SDK is indeed possible to be used for Firestore. There is no need to use react-native-firebase if your use case is very simple CRUD.
My error was that it was pulling the database content just that my render function was not displaying it.

Vue/Firestore/Firebase error on retrieve data

I am creating a Vue JS app with Firestore database but have a problem somewhere in the Firestore import (probably).
Its a simple app just storing some employee details which want to be displayed (initially) to test its working. (It doesnt!) Its just using "firebase": "^5.0.4", not vue-firebase or other plugin.
Its Firestore not the Firebase Real Time db.
So in the firebaseInit.js config file are all the basic config options which are as below
import * as firebase from 'firebase'
// Initialize Firebase
var config = {
apiKey: "AIzaSyCyKS3QxqtR9HvetpT2vWKFNxa_yeRKdhA",
authDomain: "vuefsprod-fc778.firebaseapp.com",
databaseURL: "https://vuefsprod-fc778.firebaseio.com",
projectId: "vuefsprod-fc778",
storageBucket: "vuefsprod-fc778.appspot.com",
messagingSenderId: "1048509841840"
}
firebase.initializeApp(config)
var auth = firebase.auth()
var db = firebase.database()
export function signOut (callback) {
auth.signOut().then(value => {
callback()
}, err => { callback(err) })
}
export default 'firebase/firestore'
And then the script snippet to test it is as below (in Helloworld.vue)
import db from '../firebaseInit'
export default {
name: 'home',
data () {
return {
employees: [],
loading: true
}
},
created() {
db.collections('employees').get().then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc)
const data = {
}
})
})
}
}
Yarn compiles the app which displays, but there is a warning error in console as below
[Vue warn]: Error in created hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0__firebaseInit__.a.collections is not a function"
found in
---> <Home> at src/components/HelloWorld.vue
and no data is displayed to the console, there are 6 items in the employees collection.
I'm also wondering where the "a" in a.collections comes from.
Any tips on this or a better way of doing it, say with vue-firebase or other, are more than welcome. Screenshot below.
Many Thanks
You are declaring the database with the Real Time Database (RTDB) service, instead of the Firestore service:
var db = firebase.database() // <- RTDB
You should do the following instead:
var db = firebase.firestore()
Since the RTDB does not have collections, you receive the error "collections is not a function"
FYI, the different available services are documented here: https://firebase.google.com/docs/web/setup#use_firebase_services, together with how to access/declare them.
The issue is on how you retrieving data from the firebase db
db.collections('employees')
Kindly update it to
db.collection('employees')
This should resolve this .

What's the difference between the 'firebase' module, and the "Firebase" one from Ionic Native, in Ionic

Currently found this question (which also puzzled me), but I'm currently using "firebase" to authenticate, and "Firebase" from Ionic Native to get analytics data on the Firebase console. I think that one of these is redundant (since I have the Firebase initialization data once as an object in code, and another one in google-services.json).
So what is the difference, are these two packages substitutes for each other, or is there something else.
u talk about node-modules in ionic. im using if i understand to using it. and my experience tell me its not substitutes for each other. Lets talk about the modules.
First if using:
import firebase from 'firebase'
or
import * as firebase from "firebase";
working with dataSnapshot, snapshot, snap.
if i need object to array data from firebase example:
import firebase from 'firebase';
this.addProduct = firebase.database().ref('/product-List');
this.addProduct.on('value', snapshot => {
this.productList = [];
snapshot.forEach( snap => {
this.productList.push({
category: snap.val().category,
id: snap.key,
in_stock: snap.val().in_stock,
name: snap.val().name,
downloadURL: snap.val().downloadURL,
short_description: snap.val().short_description,
description: snap.val().description,
regular_price: snap.val().regular_price,
sale_price: snap.val().sale_price,
brand: snap.val().brand,
vendor: snap.val().vendor
});
});
});
}
another node-modules ionic-native/firebase
import {Firebase} from '#ionic-native/firebase';
plugin for push notifications, event tracking, crash reporting, analytics and more.
in my case. im using for login with phone and verifyPhoneNumber example:
import {Firebase} from '#ionic-native/firebase';
constructor(private firebasePlugin: Firebase) {
}
Private registerPhone(): void {
if (!this.phoneNumber.value) {
alert('Mohon isi nomor telepon anda');
return;
}
const appVerifier = this.recaptchaVerifier;
const phoneNo = '+62' + this.phoneNumber.value;
if (this.platform.is('cordova')) {
try {
this.firebasePlugin.verifyPhoneNumber(phoneNo, 60).then (credential=> {
// alert("SMS Kode Verifikasi Berhasil dikirim ke Nomor Telp anda");
console.log(credential);
this.showPrompt(credential.verificationId);
}).catch (error => {
console.error(error);
});
}catch(error){alert(error.message)}
}
}

Resources