How to fetch unique id to delete the data in React Native Firebase - reactjs

I am using Firebase to store my data. Now i want to delete the data under Shops Section but i am not understanding that how to fetch the Unique id to delete the data here is the screen shot.
Shops
4azTPmwIpbY9vfwf9CxKMMK74kI2
-LuTY5RZLYFqeY5iPjfR
-LxMsiVGtW5xgw4XsKQi
description: "demo"
image_url_banner: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Q..."
image_url_logo: "iVBORw0KGgoAAAANSUhEUgAABLAAAAMgCAIAAAC8ggxVAAA..."
name: "demo"
tagline: "demo shop here"
Here is my code i am not able to get id of any shop
deleteItem=()=>{
let shopRef = firebase.database().ref('Shops/' + firebase.auth().currentUser.uid);
let shopId = shopRef.key;
Alert.alert("id" , shopId)
var updates = {};
updates["/Shops/" + firebase.auth().currentUser.uid + shopId] = null;
return firebase
.database()
.ref()
.update(updates);
}
please suggest some code

You need to do the following:
let shopRef = firebase.database().ref('Shops/' + firebase.auth().currentUser.uid);
shopRef.on("value",(snapshot) => {
snapshot.forEach((childSnapshot) => {
var id = childSnapshot.key;
firebase.database().ref('Shops/' + firebase.auth().currentUser.uid).child(id).remove();
});
});
First attach a listener, then iterate inside the key and retrieve it using the key property.
Check here for more information:
https://firebase.google.com/docs/database/web/read-and-write

Related

Firebase's onValue only get data once and does not update when placed inside a loop in React's useEffect

My goal is to get multiple data based on a list of data the customer requested so I put the codes inside useEffect. If the array contains the list of things the customer wants, then it grab those data from the server so the user can manipulate it. So far, it works fine but when the database updates, onValue is not triggered to grab the new data to update the render.
Here is my code. Thank you for helping me in advance.
// Getting data
useEffect(() => {
if (empDataArr.length > 1) {
let fromDay = parseInt(dateHandler(startDate).dateStamp);
let toDay = parseInt(dateHandler(endDate).dateStamp);
let tempLogArr = [];
empDataArr.forEach((emp) => {
let qLogEvent = query(child(shopRef(shopId), emp.id + "/log_events"), orderByChild("dateStamp"), startAt(fromDay), endAt(toDay));
// This is the part I need help
onValue(qLogEvent, (snap) => {
let logEventArr = [];
let val = snap.val();
if (val === null) {
} else {
Object.keys(val).forEach((key) => {
let id = key;
let dateStamp = val[key].dateStamp;
let direction = val[key].direction;
let time = val[key].timeStamp + "";
let timeStamp = time.substring(8, 10) + ":" + time.substring(10, 12);
logEventArr.push({ direction: direction, timeStamp: timeStamp, dateStamp: dateStamp, id: id });
});
tempLogArr.push({
id: emp.id,
logEvent: logEventArr,
});
}
});
});
setLogDataArr(tempLogArr.map((x) => x));
}
}, [empDataArr, shopId, startDate, endDate]);
useEffect(() => {
console.log(logDataArr);
}, [logDataArr]);
I have tried using return onValue() and const logData = onValue() but they do not work (and I do not expect the former one to work either).

Cant match users in firebase

I can't randomly get user from firebase
I'm doing dating app with react native and firebase.
Users can log in with google and set their accounts, but I can't match users.
I can pick 1 user but cant display user's data.
I tried:
i tried get all users from firebase realtime database
i can pick 1 user and log user's details but cant display in app
And sometimes user.uid returns null even if i logged in.
function getRandomUser() {
const numberOfUsers = 15;
const randomIndex = Math.floor(Math.random() * numberOfUsers);
var ref = firebase.database().ref("/users/");
ref
.limitToFirst(1)
.once("value")
.then((snapshot) => {
var randomUser = snapshot.val();
console.log(randomUser);
console.log(randomUser.bio);//this is not even display in console
});
}
I believe you should change the way you are referencing your database, so it should be var ref = firebase.database().ref("users"); and not var ref = firebase.database().ref("/users/");.
After that, are some changes related to the random number number and to the comparing issues that you need to perform, so values are returned. Please, give it a try using the below code.
var dbUser = firebase.database();
var refUser = dbUser.ref("<collection>");
refUser.orderByChild("online").equalTo(1).on("value", function(Data){
var numberOfUsers = 15;
var randomIndex = Math.random() * numberOfUsers;
var userIndex = parseInt(randomIndex, 10); //parse the random number from double to integer
var currentIndex = 0;
var BreakException = {};
try
{
Data.forEach(function(snap){
if(currentIndex==userIndex){
var randomUser = snap.val();
//Do something with your random user
throw BreakException;
}
currentIndex++;
});
}
catch(e){
if(e!== BreakException) throw e;
}
While this code is untested, it was based in this successful use case here and I believe should help you. Besides that, you can get another way of returning random users, but with indexes now, by checking this similar case here, with a very complete answer from a Product Lead from Firestore.

realtime firebase database get property name and value on child_changed

I am working on real-time fire-base database.
i have a issue in getting value what is changed in fire-base.
i have client social database inside it posts and then kkkm(this is key) and then different properties and values and what i want is to toggle approval and rejected values like that approval:true but what i get is just true/false not the property name.
toggleCheck = (id) => {
var ref = firebase.database().ref('posts/'+id);
ref.off("child_changed");
var approval;
ref.on("child_changed", function (data) {
approval = data.val();
console.log("=============================");
console.log("The updated approval is " + approval);
});
}
toggleClose = (id) => {
var ref = firebase.database().ref('posts/'+id);
ref.off("child_changed");
var rejected;
ref.on("child_changed", function (data) {
rejected = data.val();
console.log(ref.getKey());
console.log(ref.getValue());
console.log("=============================");
console.log("The updated rejected is " + rejected);
});
}
I'm not 100% sure to understand what you want to do ("toggle approval and rejected values"?) but, based on the code in your question, the following is probably what you are looking for:
var ref = firebase.database().ref('posts/' + id);
ref.on('child_changed', function(data) {
console.log(data.key); // <-- Name of the field/node that was modified
console.log(data.val()); // <-- Value of the field/node that was modified
console.log("The updated" + data.key + " is " + data.val());
});
Explanations:
data is a DataSnapshot which has:
A key property, which is "the key (last part of the path) of the location of this DataSnapshot."
A val() method, which "extracts a JavaScript value from a DataSnapshot."
UPDATE FOLLOWING YOUR COMMENTS
I understand that you want to get both the values of the approval and rejected nodes (fields) when something changes in the post.
Therefore you should use the value event type instead of the child_changed one, as follows:
var ref = firebase.database().ref('posts/' + id);
ref.on('value', function(data) {
var approved = data.val().approved;
var rejected = data.val().rejected;
var object = {'approved': approved, 'rejected': rejected};
//Do whatever you want with the object
console.log(object);
});

Angular-firebase. Data is not inserted correctly

I want my data to be inserted in firebase like so :
cities:{
Tokyo:{
name: "Tokyo, JP"
}
London:{
name: "London, UK"
}
and so on...
I inserted some data manually from the online GUI : cities
But unfortunately it gets inserted so : minsk
My code
the Firebase factory:
export default function CitiesFactory($firebaseArray, Firebase) {
'ngInject';
var ref = new Firebase("https://name.firebaseio.com/");
return $firebaseArray(ref.child('cities'));
}
Controller (add function):
$scope.addoras = function(city) {
CitiesFactory.$add({
city: {
name: city
}
}).then(function(CitiesFactory) {
var id = CitiesFactory.key();
console.log('Added Contact ' + id);
$scope.addorasmodel = '';
});
};
Can someone help me?
When you use $add() it will generate a unique push id as it says in the documentation.
If you want to avoid these unique id's you can use set() or update() (Documentation)
var ref = new Firebase("https://name.firebaseio.com/");
ref.set({
city: {
name: city
}
});
var ref = new Firebase("https://name.firebaseio.com/");
ref.update({
city: {
name: city
}
});

Accessing data from a $firebaseobject based on data from another $firebaseobject

I have the following structure on Firebase.
+Groups
-group1
-groupMessage: abc
-groupName: xyz
-members
-User1 = STATUS: "true"
-User2 = STATUS: "pending"
+group2
+group3
etc..
+Users
-User1
-Groups
-group1 = STATUS: "true"
-group3 = STATUS: "pending"
etc..
+User2
+User3
etc..
I'm trying to display group info to individual users based on whether they have a "true" or "pending" status. My app has separate page views for "pending" and "true" statuses.
Below is how I'm trying to achieve this.
.controller('GroupCtrl', function($scope, $firebaseObject, $rootScope) {
// Get a reference to the Firebase account
var fbRef = new Firebase("https://####.firebaseio.com/");
// Get a reference to where the User's Group IDs are stored
var fbUserCircle = new Firebase(fbRef + "/Users/" + $rootScope.fbAuthData.uid + "/Groups/");
var fbCircles = new Firebase(fbRef + "/Groups/");
var obj = $firebaseObject(fbUserCircle.orderByChild("Status").equalTo("pending"));
obj.$loaded().then(function() {
console.log("loaded record:", obj.$id);
// Iterating the key/value pairs of the object
angular.forEach(obj, function(value, key) {
var groupObj = $firebaseObject(fbCircles.child(key));
console.log("$ref: " + circlesObj.$ref());
circlesObj.$loaded().then(function() {
circlesObj.$bindTo($scope, "groups");
})
})
})
})
In my page view I'm trying to display {{groups.groupName}} and {{groups.groupMessage}} over ng-repeat for a user who has groups with a "pending" status.
No data is being displayed in my view for displaying a user's group with "pending" statuses. What am I doing wrong? Anyone one know of a better way of doing this?

Resources