From a5551cbc99fcebd24e0535671049b1db0b98a7a6 Mon Sep 17 00:00:00 2001 From: Julien Lengrand-Lambert Date: Tue, 24 May 2022 14:08:41 +0200 Subject: [PATCH] Saves and receives data --- src/WebBrain.ts | 53 ++++++++++++++++++++++++++++++++++++++++++-- src/models/people.ts | 1 - 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/WebBrain.ts b/src/WebBrain.ts index 881ea5c..cb29e2d 100644 --- a/src/WebBrain.ts +++ b/src/WebBrain.ts @@ -15,7 +15,11 @@ import { onAuthStateChanged } from 'firebase/auth'; +import { getFirestore, collection, Firestore, onSnapshot, addDoc } from "firebase/firestore"; + + import { FIREBASE_CONFIG } from './constants.js'; +import { IPerson } from './models/people.js'; @customElement('web-brain') export class WebBrain extends LitElement { @@ -23,24 +27,43 @@ export class WebBrain extends LitElement { @property({ type: String }) search = ''; + @property({ type: Object }) newPerson: IPerson | null = null; + @property({ type: Object }) user: User | null = null; + @property({type: Array}) persons : Array | null = null; + public firebaseApp: FirebaseApp; private auth: Auth; + private firestore : Firestore; + private provider: AuthProvider = new GoogleAuthProvider(); + private peopleCollection; + + constructor() { super(); this.firebaseApp = initializeApp(FIREBASE_CONFIG); + this.firestore = getFirestore(); this.auth = getAuth(); + this.peopleCollection = collection(this.firestore, "people"); + onAuthStateChanged(this.auth, (user) => { console.log(`onAuthStateChanged${user}`); if (user) { this.user = user;} }); + + const unsub = onSnapshot(this.peopleCollection, (querySnapshot) => { + // const cities = []; + querySnapshot.forEach((doc) => { + console.log(doc.data()); + }); + }); } static styles = css``; @@ -68,6 +91,19 @@ export class WebBrain extends LitElement { } } + async savePerson() { + console.log(`saving ${JSON.stringify(this.newPerson)}`); + + try { + const docRef = await addDoc(this.peopleCollection, this.newPerson); + console.log("Document written with ID: ", docRef.id); + } catch (e) { + console.error("Error adding document: ", e); + } + + this.newPerson = null; + } + render() { return html`

${this.title}

@@ -78,12 +114,10 @@ export class WebBrain extends LitElement { ? html`

Logged in as ${this.user.email}

` : html``} @@ -99,6 +133,21 @@ export class WebBrain extends LitElement { /> + +
+ Adding a new person + + +
+
The content will come here
diff --git a/src/models/people.ts b/src/models/people.ts index c22a9aa..10b4098 100644 --- a/src/models/people.ts +++ b/src/models/people.ts @@ -1,5 +1,4 @@ export interface IPerson { - id?: string | null, name: string, createdAt?: Date | null, updatedAt?: Date | null,