ive had a lot of trouble with firebase arrays, im now using push
I have this
I want to pull all the users down so I do this:
export const pullFromFirebase = () => {
return firebase
.database()
.ref("/users/")
.once("value")
.then(snapshot => {
var users = [];
snapshot.forEach(user => {
users.push(user.val());
});
return users;
});
};
this is fine
however, I now need the unique id -LI7d_i_BmrXktzMoe4p that firebase generated for me so that I can access this record (i.e. for updating and deleting) how do i do this?
You can get the key of the snapshot with the key property: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#key
So you could change your code to this:
export const pullFromFirebase = () => {
return firebase
.database()
.ref("/users/")
.once("value")
.then(snapshot => {
var users = [];
snapshot.forEach(user => {
let userObj = user.val();
userObj.id= user.key;
users.push(userObj);
});
return users;
});
};
You can change this part:
snapshot.forEach(user => {
users.push(user.val());
});
To instead be:
let usersObj = snapshot.val()
for (var user_id in usersObj) {
users.push(Object.assign(usersObj[user_id], {
user_id: user_id,
});
});
That way, instead of each element in the users array only having email, name and username fields, it has user_id as well.
Related
I first try to get the data from firebase, then call a function to update the outer variable (setdata). The function however creates a local variable and doesnt update the outer one.
I was wondering how I can update the outer variable?
import * as firebase from 'firebase';
function userData() {
var userInfo
firebase.auth().onAuthStateChanged(user => {
if (user) {
getUserData(user.uid)
}
})
function getUserData(uid) {
firebase
.database()
.ref('users/' + uid)
.once("value")
.then(function (snapshot){
setData(snapshot.val())
})
}
function setData(data){
userInfo.name = data.name;
userInfo.username = data.username;
}
return({ nameOf: userInfo.name, usernameOf: userInfo.username});
}
export default userInformation = {
name: userData().nameOf,
username: userData.usernameOf,
}
I think the problem is in the way you handled it. Please try this way and let me know if it worked. It should work...
userData.js
export default function userData() {
return firebase.auth().onAuthStateChanged((user) => {
if (user) {
return getUserData(user.uid);
}
});
function getUserData(uid) {
return firebase
.database()
.ref('users/' + uid)
.once('value')
.then(function (snapshot) {
const data = snapshot.val();
return { name: data.name, username: data.username };
});
}
}
When you want to use the above function,
import userData from 'path/to/userData/js';
const userInformation = userData();
Did the following and got results,
var usr = firebase.auth().currentUser;
var usrId = usr.uid;
var ref = firebase.database().ref('users/' + usrId)
var latestSnapshot = null;
ref.on('value', function(snap) { latestSnapshot = snap.val(); });
export default latestSnapshot````
var emp = db.collection('BookedTicketData').get().then((snapshot) => {
snapshot.docs.forEach((doc) => {
data = doc.data();
bseat = data.AllSeat
// console.log(bseat)
allseat.concat(bseat)
})
console.log(allseat)
return allseat;
}).then((alls) => {
console.log(alls)
})
I have done this code to get the array from the doucumnets of firebase and it is coming seperatly i want to combine all the array in single array and print the array in console.log(alls)
1-> [4,46,324,346,345,234,3446,36]
2-> [324,6,3,44,6,2,6,35,2,7,23]
alls -> [4,46,324,346,345,234,3446,36,3244,6,3,44,6,2,6,35,2,7,23]
If I correctly understand your question, the following should do the trick:
var emp = db
.collection('BookedTicketData')
.get()
.then((snapshot) => {
let allseat = [];
snapshot.docs.forEach((doc) => {
data = doc.data();
bseat = data.AllSeat;
// console.log(bseat)
allseat = allseat.concat(bseat);
});
console.log(allseat);
return allseat;
})
This is my database structure below tutorCopy is the currentId of the user on basis of which I have to retrieve the user email but the problem is I can't get it, I have tried two methods but both are not working:
1st method with promise
componentWillMount(){
let user = firebase.auth().currentUser.uid;
const emailFetch = ["useremail"]
const emailpromise = emailFetch.map(id => {
return firebase.database().ref("tutorCopy/").child(user).child(id).on('value', s => s)
})
Promise.all(emailpromise)
.then(user => {
this.setState({ markers: s.values(s.val()) })
})
.catch(err => {
console.log(err)
})
}
Other one with snapshot:
componentWillMount(){
var user = firebase.auth().currentUser.uid;
var currId = JSON.stringify(user);
firebase.database().ref("tutorCopy/").child('user').once("value", snapshot => {
this.setState({ markers: Object.values(snapshot.val()) })
})
}
Hello, I have made Firebase function which is watching if users matched.
All parts work, but i added one more method getUserDataById where i want to get extra data from users, it returns undefined.
So this is what i tried:
exports.UserPressesLike = functions.database
.ref('/users/{userId}/matches/{otherUserId}')
.onCreate(async (snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
const userId = context.params.userId;
const matchedUserId = context.params.otherUserId;
const a = await checkUserMatch(userId, matchedUserId);
if (a === true) {
console.log('Its a match');
addNewChat(userId, matchedUserId);
//create chat for both users
} else {
console.log('There is no match');
//do nothing
console.log(a);
}
return null;
});
checkUserMatch = async (userId, matchedUserId) => {
const isLiked = await admin
.database()
.ref('/users/' + matchedUserId + '/matches/' + userId)
.once('value')
.then(snapshot => {
// let tempuserId = snapshot.val();
// if()
let isLiked = snapshot.exists();
console.log(isLiked);
return isLiked;
})
.catch(error => {
console.log(error);
return snapshot;
});
return isLiked;
};
addNewChat = async (userId, matchedUserId) => {
const user1 = await getUserDataById(userId);
const user2 = await getUserDataById(matchedUserId);
console.log(JSON.stringify('User data: ' + user1));
const snapshot = await admin
.database()
.ref('/chats')
.push({
members: { [userId]: true, [matchedUserId]: true },
[userId]: { username: [user1.username] },
[matchedUserId]: { username: [user2.username] },
});
};
getUserDataById = async userId => {
const snapshot = await admin
.database()
.ref('/users/' + userId)
.once('value')
.then(childsnapshot => {
let data = childsnapshot.val();
return data;
});
};
But I get error:
TypeError: Cannot read property 'username' of undefined
at addNewChat (/srv/index.js:93:36)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
The problem is in getUserDataById method. Because it returns undefined.
Where I made mistake?
Why I get username: { 0 : emilis} it should be username: emilis??
Part 1: getUserDataById returns undefined
You forgot return snapshot in your async function. (However, as it as a plain object, not a snapshot, I would rename the variable)
getUserDataById = async userId => {
const userData = await admin
.database()
.ref('/users/' + userId)
.once('value')
.then(childsnapshot => {
let data = childsnapshot.val();
return data;
});
return userData;
};
However, I would flatten it to the following (which is identical to the above, yet concise):
getUserDataById = userId => {
return admin
.database()
.ref('/users/' + userId)
.once('value')
.then(childsnapshot => childsnapshot.val());
};
Part 2: Why is my data returned as {username: {0: "Emilis"}}?
{0: "Emilis"} being returned as an object, not an array, is caused by how Firebase stores arrays in the Realtime Database. There is quite a comprehensive article on arrays on the Firebase Blog covering these quirks which I recommend reading. I'll summarise the key ones here.
When any array is stored in the Realtime Database it is stored in it's object form where {username: [user1.username] } will be stored as {username: {0: "someusername"} }. Because JSON is typeless, the Realtime Database no longer understands this entry to be an array. An array with multiple entries will also be stored stored as a plain object ([value1, value2] will become {0: value1, 1: value2}).
When the Firebase JavaScript SDK downloads data from the Realtime Database, it checks the keys of any objects for a mostly sequential numeric sequence (0,1,2,3,... or 0,1,3,4,...) and if detected, converts it to an array using null for any missing entries.
As {0: value1, 1: value2} contains the sequential keys 0 and 1, it will be parsed as [value1, value2].
As {0: "someusername"} does not contain a sequence of keys, it is returned as-is.
To bypass this, remove the single entry array and use it's value directly (as below) or explicitly convert it to an array in your client code.
addNewChat = async (userId, matchedUserId) => {
const user1 = await getUserDataById(userId);
const user2 = await getUserDataById(matchedUserId);
console.log(JSON.stringify('User data: ' + user1));
return admin // don't forget to return the Promise!
.database()
.ref('/chats')
.push({
members: { [userId]: true, [matchedUserId]: true }, // FYI: these are "use value as the key" instructions not arrays.
[userId]: { username: user1.username },
[matchedUserId]: { username: user2.username },
});
};
I have in firebase firestore a Collection named users created with docs of unique id.
Now I would like to push them in an Array.
(In the usersCollection there are 3 users stored with the currentUser.uid)
Example:
fb.usersCollection.where("state", "==", 'online').get().then(querySnapshot => {
querySnapshot.forEach((doc) => {
const userName = doc.data().name
this.markerMy = { name: userName }
})
// push userName inside randomArray
const randomArray = []
randomArray.push(this.markerMy)
I only get it so that I can push one user inside the Array, but not more.
You should declare randomArray before fb.usersCollection and call the push operation inside the callback as follows :
const randomArray = []
fb.usersCollection.where("state", "==", 'online').get().then(querySnapshot => {
querySnapshot.forEach((doc) => {
const userName = doc.data().name
this.markerMy = {
name: userName
}
randomArray.push(this.markerMy)
})
});