I want to return and object that I create in a Firestore call to my UI component. Upon a lot of research regarding using async functions and .then() to receive data from a function, I still cannot get it to work. I just get undefined. Most answers I have found say that I should use await and/or .then() when handling the response so not to just get a promise. But nothing I have tried gets some actual data. The object is always undefined.
Firebase config:
export const getLatestAcceptedSample = async (bottleID, equipmentID) => {
let msg = {}
try {
await db.collection('Oil Samples').orderBy('createdAt', 'desc').limit(1).get().then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
const tempMsg = documentSnapshot.data()
if (bottleID === tempMsg.bottleID && equipmentID === tempMsg.equipmentID) {
msg = {
bottleID: tempMsg.bottleID,
equipmentID: tempMsg.equipmentID,
timestamp: tempMsg.createdAt?.toDate() ?? '',
userName: tempMsg.authorName,
userID: tempMsg.authorID,
title: tempMsg.title
}
console.log(msg)
return msg
} else {
alert("Fetching data from database failed")
}
return msg
})
})
}
catch {
alert('Get Latest Sample error')
}
}
UI component that calls the function:
export default function SampleAcceptedScreen(props) {
const { bottleID, equipmentID } = props.route.params
const [docBottleID, setDocBottleID] = useState('')
const [docEquipmentID, setDocEquipmentID] = useState('')
const [userName, setUserName] = useState('')
useEffect(() => {
try {
FirestoreService.getLatestAcceptedSample(bottleID, equipmentID).then((msg) => {
console.log(msg)
setDocBottleID(msg.bottleID)
setDocEquipmentID(msg.equipmentID)
setUserName(msg.userName)
})
}
catch {
console.log(error)
}
})
return (
<View style={styles.container} >
<CustomHeader title="Sample Accepted" navigation={props.navigation} isHome={false} />
<View style={styles.contentContainer} >
<Text style={styles.header} >Oil sample has been registered!</Text>
<Text style={styles.header2} >The following details have been associated with the sampling:</Text>
<Text>User: {userName} </Text>
<Text>Bottle barcode: {docBottleID} </Text>
<Text>Equipment barcode: {docEquipmentID} </Text>
<TouchableOpacity style={styles.button}
onPress={() =>
props.navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'HomeScreen' },
{
name: 'HomeScreen',
params: { bottleID: undefined, equipmentID: undefined }
}
]
})
)} >
<Text style={styles.buttonText} >Accept</Text>
</TouchableOpacity>
</View>
</View>
);
}