Syncs messages automagically

This commit is contained in:
Julien Lengrand-Lambert
2022-04-01 16:37:43 +02:00
parent 7ff2816897
commit be4cd6a15f
3 changed files with 37 additions and 6 deletions

View File

@@ -25,9 +25,12 @@ external object FirebasePorts{
fun saveMessage(uid: String, message: String)
fun getMessages(uid: String) : Promise<Array<FirestoreMessage>>
fun syncMessages(uid:String, callback: (Array<FirestoreMessage>?) -> Unit)
}
fun main() {
var user : FirebaseUser? by mutableStateOf(null)
var error : String? by mutableStateOf(null)
var message : String by mutableStateOf("")
@@ -48,7 +51,11 @@ fun main() {
onClick {
error = null
FirebasePorts.logIn()
.then { user = it }
.then { user = it;
// Subscribes to receiving new messages
FirebasePorts.syncMessages(it.uid) { newMessages -> messages = newMessages }
}
.catch { error = it.message }
}
}) {
@@ -88,7 +95,6 @@ fun main() {
TextArea(value = message,
attrs = {
onInput {
console.log(it.value)
message = it.value
}
})
@@ -96,9 +102,6 @@ fun main() {
Button(attrs = {
onClick {
error = null
console.log(JSON.stringify(user))
console.log(user)
console.log(user!!.uid)
FirebasePorts.saveMessage(user!!.uid, message)
message = ""
}

View File

@@ -1,7 +1,7 @@
import {FIREBASE_CONFIG} from "./constants";
import { initializeApp } from "firebase/app";
import { getAuth, signInWithPopup, GoogleAuthProvider, signOut } from "firebase/auth";
import { collection, addDoc, getFirestore, getDocs} from "firebase/firestore";
import { collection, addDoc, getFirestore, getDocs, onSnapshot, query} from "firebase/firestore";
const firebaseApp = initializeApp(FIREBASE_CONFIG);
const provider = new GoogleAuthProvider();
@@ -47,4 +47,21 @@ export async function getMessages(uid){
});
return messages;
}
export async function syncMessages(uid, callback){
console.log("syncMessages activated!");
const q = query(collection(firestore, `users/${uid}/messages`));
onSnapshot(q, (querySnapshot) => {
const messages = [];
querySnapshot.forEach((doc) => {
messages.push({
id: doc.id,
content: doc.data().content
})
});
callback(messages);
});
}