I have a functioning React Native Expo App that interacts with my Firebase Realtime Database. In short, I am stumped trying to find a means of checking across all child values to see if a value exists, before writing that value (again) as a new record to the database.
I historically have been getting "ExponentPushToken" from Expo's Push Notification API within my App.js and then immediately writing a new record to my Firebase Realtime Database using the following code within the same function for registering for Push Notifications from Expo's Push Notification API:
const token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
var userListRef = firebase.database().ref("users/push_token");
var newUserRef = userListRef.push();
newUserRef.set(token);
I also have the following code reading the database and logging to console the correct information I need to be able to compare all of the outputted values to the aforementioned "token" value:
var userListRef = firebase.database().ref("users/push_token");
userListRef.on("value", function (snapshot) {
snapshot.forEach(function (child) {
console.log(child.val());
});
});
Where I continue to hit a wall is in trying to take the acquired "token" and confirm that it is not already a "child.val()" (an existing value across the db) in my Firebase Realtime DB before I .push()
and .set()
to create a new record in said DB. I'd love to be able to log to console to verify too. The code below does not work... My attempt here is to try to .push()
to an array and see if the "token" is somewhere in the array. This is happening but my last function with the "if/else" statement is is still looping for each record in the database. Not sure how to write this without looping the subsequent functions for every record in the database.
const token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
var userListRef = firebase.database().ref("users/push_token");
userListRef.once("value", function (snapshot) {
snapshot.forEach(function (child) {
createPushTokenArray(child.val());
myTokenHandler(token);
});
});
var allPushTokens = [];
async function createPushTokenArray(dbState) {
allPushTokens.push(dbState);
return;
}
async function myTokenHandler(myToken) {
await createPushTokenArray();
var checkForValue = allPushTokens.includes(myToken);
if (checkForValue === true) {
return console.log("Push Token already stored in database.");
} else {
var userListRef = firebase.database().ref("users/push_token");
var newUserRef = userListRef.push();
var writeNewToken = newUserRef.set(myToken);
writeNewToken;
return console.log("New Push Token stored in database.");
}
}
My numerous attempts to try to get anywhere in all of this have been futile. For reference, here is the db structure below (in JSON format):
{
"users" : {
"push_token" : {
"key or name" : "value",
"-Maer1EuNpR24LdhxmIl" : "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
}
}
}