-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathApp.js
97 lines (86 loc) · 2.98 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
// @refresh reset
import React, { useState, useEffect, useCallback } from 'react'
import { GiftedChat } from 'react-native-gifted-chat'
import AsyncStorage from '@react-native-community/async-storage'
import { StyleSheet, TextInput, View, YellowBox, Button } from 'react-native'
import * as firebase from 'firebase'
import 'firebase/firestore'
const firebaseConfig = {
//Your firebase config here
}
if (firebase.apps.length === 0) {
firebase.initializeApp(firebaseConfig)
}
YellowBox.ignoreWarnings(['Setting a timer for a long period of time'])
const db = firebase.firestore()
const chatsRef = db.collection('chats')
export default function App() {
const [user, setUser] = useState(null)
const [name, setName] = useState('')
const [messages, setMessages] = useState([])
useEffect(() => {
readUser()
const unsubscribe = chatsRef.onSnapshot((querySnapshot) => {
const messagesFirestore = querySnapshot
.docChanges()
.filter(({ type }) => type === 'added')
.map(({ doc }) => {
const message = doc.data()
//createdAt is firebase.firestore.Timestamp instance
//https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
return { ...message, createdAt: message.createdAt.toDate() }
})
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
appendMessages(messagesFirestore)
})
return () => unsubscribe()
}, [])
const appendMessages = useCallback(
(messages) => {
setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
},
[messages]
)
async function readUser() {
const user = await AsyncStorage.getItem('user')
if (user) {
setUser(JSON.parse(user))
}
}
async function handlePress() {
const _id = Math.random().toString(36).substring(7)
const user = { _id, name }
await AsyncStorage.setItem('user', JSON.stringify(user))
setUser(user)
}
async function handleSend(messages) {
const writes = messages.map((m) => chatsRef.add(m))
await Promise.all(writes)
}
if (!user) {
return (
<View style={styles.container}>
<TextInput style={styles.input} placeholder="Enter your name" value={name} onChangeText={setName} />
<Button onPress={handlePress} title="Enter the chat" />
</View>
)
}
return <GiftedChat messages={messages} user={user} onSend={handleSend} />
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
padding: 30,
},
input: {
height: 50,
width: '100%',
borderWidth: 1,
padding: 15,
marginBottom: 20,
borderColor: 'gray',
},
})