Hi! Iām creating a dapp chat and trying to set a Room parent for the message. The Room has 2 peers, one is the main user that is initiating it and the other is the peer the message is sent to.The problem is when I try to add the peer to the room created by the main user as it created another one.Also the message between the two peers, how should it work because the null error pointer comes from messaging from the peer side as it says the currentRoom value is null. How can I do it so that both users can send message to one another in the same chat room? This is the code I have so far:
async function openChatRoom(event){
// const params = {"userMain": event, "peer": user.get("username")}
const currentUser = user.get("username")
const queryRoom = new Moralis.Query("ChatRooms")
const peerRoom = new Moralis.Query("ChatRooms")
await peerRoom.equalTo("peer", currentUser)
const peerResult = await peerRoom.find()
//currentRoom.id = roomId
const subscription = await queryRoom.subscribe()
subscription.on('open', async()=>{
await queryRoom.equalTo("userMain",currentUser)
const resultRoom = await queryRoom.first()
console.log("Peer result",peerResult)
// console.log(peerResult)
if(!resultRoom && !peerResult){
await currentRoom.set("userMain", currentUser)
await currentRoom.set("peer",event)
await currentRoom.save()
setReceiver(event)
setRoomId(currentRoom.id)
console.log("object created!")
alert("open!")
}else if(resultRoom || peerResult){
console.log(peerResult)
setRoomId(peerResult.id)
currentRoom.id = roomId
const query = new Moralis.Query("Messages")
await query.equalTo("roomId", peerResult.id)
const resultMessage =await query.find()
console.log("Already created!")
setReceiver(event)
// console.log("PEer",peerResult)
console.log(peerResult)
console.log("currentroom", currentRoom)
// console.log(peerResult[0].attributes.peer)
console.log(roomId)
setMessages(resultMessage)
console.log(messages)
}else{
console.log("Not working")
}
})
}
async function writeMessage(e){
console.log(roomId)
if(e!='undefined' && e.length >0)
{
currentRoom.id = roomId
console.log(roomId)
console.log("Current room",currentRoom.id)
const query = new Moralis.Query("ChatRooms")
await currentMessage.set("message",e)
await currentMessage.set("sender",userMain)
await currentMessage.set("roomId",roomId)
await currentMessage.set("read",false)
await currentMessage.set("parent",currentRoom)//here i get the error on the peer side
console.log(currentRoom)
await currentMessage.save()
console.log(message)
console.log(roomId)
const newMessage={ message:e, sender:userMain, createdAt:JSON.stringify(currentMessage.createdAt), read:false, roomId:roomId}
setMessage(newMessage)
console.log(newMessage.read)
setMessages(messages=>[...messages,{
attributes: newMessage
}])
}
}