-
-
Notifications
You must be signed in to change notification settings - Fork 683
/
Copy pathApp.js
123 lines (85 loc) · 2.6 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import React, { useRef, useState } from 'react';
import './App.css';
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import 'firebase/analytics';
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
firebase.initializeApp({
// your config
})
const auth = firebase.auth();
const firestore = firebase.firestore();
const analytics = firebase.analytics();
function App() {
const [user] = useAuthState(auth);
return (
<div className="App">
<header>
<h1>⚛️🔥💬</h1>
<SignOut />
</header>
<section>
{user ? <ChatRoom /> : <SignIn />}
</section>
</div>
);
}
function SignIn() {
const signInWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider);
}
return (
<>
<button className="sign-in" onClick={signInWithGoogle}>Sign in with Google</button>
<p>Do not violate the community guidelines or you will be banned for life!</p>
</>
)
}
function SignOut() {
return auth.currentUser && (
<button className="sign-out" onClick={() => auth.signOut()}>Sign Out</button>
)
}
function ChatRoom() {
const dummy = useRef();
const messagesRef = firestore.collection('messages');
const query = messagesRef.orderBy('createdAt').limitToLast(25);
const [messages] = useCollectionData(query, { idField: 'id' });
const [formValue, setFormValue] = useState('');
const sendMessage = async (e) => {
e.preventDefault();
const { uid, photoURL } = auth.currentUser;
await messagesRef.add({
text: formValue,
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
uid,
photoURL
})
setFormValue('');
dummy.current.scrollIntoView({ behavior: 'smooth' });
}
return (<>
<main>
{messages && messages.map(msg => <ChatMessage key={msg.id} message={msg} />)}
<span ref={dummy}></span>
</main>
<form onSubmit={sendMessage}>
<input value={formValue} onChange={(e) => setFormValue(e.target.value)} placeholder="say something nice" />
<button type="submit" disabled={!formValue}>🕊️</button>
</form>
</>)
}
function ChatMessage(props) {
const { text, uid, photoURL } = props.message;
const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received';
return (<>
<div className={`message ${messageClass}`}>
<img src={photoURL || 'https://api.adorable.io/avatars/23/[email protected]'} />
<p>{text}</p>
</div>
</>)
}
export default App;