mirror of
https://github.com/jlengrand/kotlin-ports-demo.git
synced 2026-03-10 08:31:20 +00:00
Syncs messages automagically
This commit is contained in:
@@ -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 = ""
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user