Created
May 26, 2020 03:58
-
-
Save mrcflorian/d196fd9a0a77188240ab73b66ec46f3c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react' | |
import { FlatList, Keyboard, Text, TextInput, TouchableOpacity, View } from 'react-native' | |
import styles from './styles'; | |
import { firebase } from '../../firebase/config' | |
export default function HomeScreen(props) { | |
const [entityText, setEntityText] = useState('') | |
const [entities, setEntities] = useState([]) | |
const entityRef = firebase.firestore().collection('entities') | |
const userID = props.extraData.id | |
useEffect(() => { | |
entityRef | |
.where("authorID", "==", userID) | |
.orderBy('createdAt', 'desc') | |
.onSnapshot( | |
querySnapshot => { | |
const newEntities = [] | |
querySnapshot.forEach(doc => { | |
const entity = doc.data() | |
entity.id = doc.id | |
newEntities.push(entity) | |
}); | |
setEntities(newEntities) | |
}, | |
error => { | |
console.log(error) | |
} | |
) | |
}, []) | |
const onAddButtonPress = () => { | |
if (entityText && entityText.length > 0) { | |
const timestamp = firebase.firestore.FieldValue.serverTimestamp(); | |
const data = { | |
text: entityText, | |
authorID: userID, | |
createdAt: timestamp, | |
}; | |
entityRef | |
.add(data) | |
.then(_doc => { | |
setEntityText('') | |
Keyboard.dismiss() | |
}) | |
.catch((error) => { | |
alert(error) | |
}); | |
} | |
} | |
const renderEntity = ({item, index}) => { | |
return ( | |
<View style={styles.entityContainer}> | |
<Text style={styles.entityText}> | |
{index}. {item.text} | |
</Text> | |
</View> | |
) | |
} | |
return ( | |
<View style={styles.container}> | |
<View style={styles.formContainer}> | |
<TextInput | |
style={styles.input} | |
placeholder='Add new entity' | |
placeholderTextColor="#aaaaaa" | |
onChangeText={(text) => setEntityText(text)} | |
value={entityText} | |
underlineColorAndroid="transparent" | |
autoCapitalize="none" | |
/> | |
<TouchableOpacity style={styles.button} onPress={onAddButtonPress}> | |
<Text style={styles.buttonText}>Add</Text> | |
</TouchableOpacity> | |
</View> | |
{ entities && ( | |
<View style={styles.listContainer}> | |
<FlatList | |
data={entities} | |
renderItem={renderEntity} | |
keyExtractor={(item) => item.id} | |
removeClippedSubviews={true} | |
/> | |
</View> | |
)} | |
</View> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment