First time Firebase and RN user here, trying to figure out how to transmit the Device ID/Token of the app user.
I'm using something basic like this to transmit information to my firebase database right now (using firebase.database().ref()
).
updateDB = (timestamp_key, item_name, item_url) => {
firebase.database().ref(timestamp_key).set({
item_name: item_name,
item_url: item_url
})
}
I haven't been able to find a simple straightforward answer as to how to fetch one's device token and transmit that as well (so I know whose action is whose later).
Is there a (what I think should be) a relatively straightforward way to do that? Thanks!
P.S. I am calling this higher up in the script in addition to the configs to initialize the connection -- maybe it's somewhere around here I need to grab the device token?
// Initialize Firebase
const firebaseConfig = {
apiKey: "blah",
authDomain: "blah",
databaseURL: "blah",
storageBucket: "blah",
messagingSenderId: "blah"
};
firebase.initializeApp(firebaseConfig);
Click on 'Cloud Messaging' and then "New Notification" Send a test notification. If you receive a notification then your code is fine. BTW you should use the "Topic" implementation rather than the "Token" implementation. It will make this process of sending Notifications very easy and manageable.
The Firebase Admin SDK has a built-in method for verifying and decoding ID tokens. If the provided ID token has the correct format, is not expired, and is properly signed, the method returns the decoded ID token. You can grab the uid of the user or device from the decoded token.
So I'm using Expo with React Native as well. However, I'm using Google's Cloud Firestore instead of realtime database.
I'm not sure I understand your question completely, but this is how I am doing it:
const firebase = require('firebase');
import { Constants } from 'expo';
// Required for side-effects
require('firebase/firestore');
import { firebaseConfig } from './../keys';
class Fire {
constructor() {
this.init();
this.observeAuth();
}
init = () => firebase.initializeApp(firebaseConfig);
observeAuth = () => firebase.auth().onAuthStateChanged(this.onAuthStateChanged);
onAuthStateChanged = user => {
if (!user) {
try {
firebase.auth().signInAnonymously();
} catch ({ message }) {
console.warn(message);
}
} else {
this.saveUser();
}
};
saveUserInfo = () => {
const { uid } = this;
if (!uid) {
return;
}
// You can add any information here
const info = {
deviceId: Constants.deviceId,
};
const ref = this.db.collection('users').doc(uid);
const setWithMerge = ref.set({ uid, ...info }, { merge: true });
};
get db() {
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
}
Fire.shared = new Fire();
export default Fire;
I got most of this code from Evan Bacon's example - https://github.com/EvanBacon/Expo-Pillar-Valley.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With