I'm creating a messaging app with react-native & firebase. Its working quite alright.
Now i want to take it a step further by creating private chats. To my understanding, i need to populate the data into subcollections. e.g : chats>chatroom1>data
, chats>chatroom2>data e.t.c
I'm currently working with this code
import firebase from 'firebase';
class Fire {
constructor (props) {
this.init()
this.checkAuth()
}
init = () => {
if (!firebase.apps.length) {
}
};
checkAuth = () => {
firebase.auth().onAuthStateChanged(user => {
if (!user) {
firebase.auth().signInAnonymously();
}
})
}
send = messages => {
messages.forEach(item => {
const message = {
text: item.text,
timestamp: firebase.database.ServerValue.TIMESTAMP,
user: item.name
}
this.db.push(message)
})
}
parse = message => {
const {user, text, timestamp} = message.val();
const {key, _id} = message
const createdAt = new Date(timestamp)
return {
_id,
createdAt,
text,
user
}
}
get = callback => {
this.db.on('child_added', snapshot => callback(this.parse(snapshot)))
}
off() {
this.db.off()
}
get db() {
return firebase.database().ref("messages");
}
get uid(){
return(firebase.auth().currentUser || {}).uid
}
}
How can I populate the subcollections from this code?
I believe for calling out of specific subcollections, firebase.database().ref("messages/chatroomid");
will do the trick, right?
what i mean by sub collection is this
Currently my JSON tree looks like:
database
- messages
- mvhhsjsfurhcb
- text: "hi"
timestamp: 9942313949
user: "David"
firebase.database().ref("messages"); calls out the data under messages
This is what i want
database
- messages
-chatroom1
- mvhhsjsfurhcb
- text: "hi"
timestamp: 9942313949
user: "David"
-chatroom2
- mvhhsjsfurhcb
- text: "hey, this i room2"
timestamp: 9942313949
user: "Sam"
Then for firebase.database().ref("messages/chatroom1");
to call out only messages in chatroom1.
What I intend to achieve with this is to create a private chat for users
To give you more insight, if I was to do this with PHP, I would be doing SELECT * WHERE chatroom = :chatroom;
i believe the answer will be related to this.db.push(message)
. maybe adding another '.' indicating that there's another branch before pushing the message