I am using react native and firebase realtime database to store and query a list of properties. It seems that when I run the below query in XCode for iOS the array created here shows a list of the property objects. However, when I run this android studio the array is empty. Do you know what may be causing this? Can someone please help here I am very new to react native and using firebase realtime database?
I really do apologies for the poor code formatting:
const array = []
await db.ref(`users/`).on(`value`, snapshot => {
if (snapshot.exists()) {
snapshot.forEach(function(userSnapshot){
if(userSnapshot.hasChild("properties")){
userSnapshot.child("properties").forEach((propertySnapshot) => {
array.push({
key: userSnapshot.key,
property: propertySnapshot.val(),
username: userSnapshot.val().username,
email: userSnapshot.val().email,
phoneNumber: (userSnapshot.val().phoneNumber != null)?userSnapshot.val().phoneNumber:null,
propertyName: propertySnapshot.key,
profile_pic: userSnapshot.val().profile_pic,
connectedAccount_id: (userSnapshot.val().connectedAccount_id != null)?userSnapshot.val().connectedAccount_id:null,
customer: (userSnapshot.val().customer != null)?userSnapshot.val().customer:null,
});
})
}
})
}
});
await database().ref(`users/${auth().currentUser.uid}/your_location`).once(`value`, function(snap){
....
Geocoder.init("******");
Geocoder.from(locationPostcode)
.then(json => {
var location = json.results[0].geometry.location;
global.latitude = location.lat;
global.longtitude = location.lng;
})
.catch(error => console.warn(error));
console.log("array result "+array)
.....
})
The log array shows an array of objects for iOS:
array result [object Object],[object Object],[object Object],[object Object],[object Object]
but for android it's empty:
array result
Related
I'm writing an app using React Native and I came across an issue when trying to update an Object with the useState method. Here's my code:
const Screen = ({route}) => {
var roomKey = route.params;
const [room, setRoom] = useState({});
db.ref('rooms').on('value', (data) => {
setRoom(() => (data.val())[roomKey]);
});
console.log(room);
// rest of the code ...
My code works as follows: first it takes a key outputted by another screen with react navigation, and then calls the firebase database with the ref method (db is defined as Firebase.initializeApp(config).database(), where config is the object with all the firebase datas needed). If I log out the data.val())[roomKey] it correctly outputs the object I'm downloading from database, however the room object is not updated by the useState method (it outputs undefined, making the following part of the code crash). What am I doing wrong?
In your code, setRoom is a function to change the value of room state. So, you have to pass the value into the setRoom.
Please check the following code.
const Screen = ({route}) => {
var roomKey = route.params;
const [room, setRoom] = useState({});
db.ref('rooms').on('value', (data) => {
setRoom(data.val()[roomKey]);
});
console.log(room);
// rest of the code ...
I am trying to deploy a simple Firebase Cloud function.
I want to use Firestore to reward a referrer with in-app credits when someone that they referred signs up.
This is my node.js function.
exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate(event => {
let documentRef = admin.firestore.doc(`users/${event.data.referredBy}/cats/accountInformation`);
console.log("Error giving hints:", documentRef);
return documentRef.data.ref.set({
credits: credits + 5
.catch(error => {
console.log("Error giving hints:", error);
}),
}, {
merge: true
});
});
I am quite unfamiliar with node.js. I have looked around and tried different things as far as syntax, and none of them have worked. Any help would be appreciated. I can't find much documentation on this.
Heres an example of how to drag the written information without making another request, just with the onCreate firestore event:
exports.createUser = functions.firestore.document('users/{userId}').onCreate(event => {
//Doc ref
let documentRef = admin.firestore.doc(`users/${event.data.referredBy}/cats/accountInformation`);
//Get the value you want from that document
documentRef.get().then((doc) => {
var docData = doc.data();
var currentCredits = docData.credits;
var newCredits = currentCredits + 5;
//Then you return the promise, this time pointing the new ref
return documentRef.set({credits:newCredits});
});
});
Do you know how I can populate the reference Field on a Document using Firestore?
When you create / get a document reference, you can save this into another document. This example is for the Node SDK, but it should give you an idea of how to implement this for Android.
Creating a document reference
// Create the references
let myFirstDoc = db.collection('myCollection').doc();
let mySecondDoc = db.collection('otherCollection').doc();
let batch = db.batch();
// Save the two documents to the batch
batch.set(myFirstDoc, {someData: true});
batch.set(mySecondDoc, {firstDocRef: myFirstDoc});
// Commit the batch
return batch.commit()
.then(response => {
console.log('Data saved');
})
.catch(err => {
console.error(err);
});
Getting an existing reference
return db.collection('myCollection').doc('myDocId')
.then(documentSnapshot => {
let newDoc = db.collection('otherCollection').add({otherDoc: documentSnapshot.ref});
})
.then(response => {
console.log('Data saved');
})
.catch(err => {
console.error(err)
})
So I'm using the most recent version of Ionic2 (v3.4) and I'm trying to get the ionic native SQLite to work. I've been able to create database file and put a table in it like so:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql(tableQuery, {})
.then(() => console.log("success"))
.catch(() => console.log("fail"));
})
Inserting works too. But when I try to get the result of a selection:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql("SELECT * FROM savedCoupons where itemId=" + itemId, {})
.then((db) => {console.log(JSON.stringify(db))})
.catch(() => console.log("***ERROR WITH SELECT***"));
})
.catch(() => console.log("ERROR: FAILED TO CREATE/OPEN DATABASE."));
I get lost because of the lack of documentation. JSON.stringify() is being run so it would seem the query worked. It returns {"rows":{"length":1}, "rowsAffected":0} and that's it. How do I access the result of the query?
Let you have three columns e.x id,name,lastname in your table.
after querying you can access it like:
db.executeSql('SELECT * FROM student WHERE id='+1, {})
.then(result => {
for (var i = 0; i < result.rows.length; i++) {
console.log("---Id---"+result.rows.item(i).id);
console.log("---Name---"+result.rows.item(i).name);
console.log("---Lastname---"+result.rows.item(i).lastname);
}
});
I'm using the following plugin https://github.com/EddyVerbruggen/nativescript-plugin-firebase allowing to access Firebase from Nativescript applicaiton.
For some reasons, when I do a query request to get my objects, some properties of the json objects are missed.
Below the query :
return firebase.query(
data => {
if(data.value) {
Object.keys(data.value).forEach(key => {
this.results.push(data.value[key]); // Here I dont get exactly the JSON, some properties disapears.....
}
}
}, "/ads/",
{ orderBy: { type: firebase.QueryOrderByType.KEY }})
.then(result => { return result; })
);
My database
Properties of type number are not loaded (totalProduct and state).
Regards
I find out that your forEach miss a ')'.
After modified, everything is fine. All of the JSON properties still exist.