EDIT: I'm new to Stack, but why was my earlier thread locked? It just said "similar thread is found somewhere else" and the thread wasn't at all similar.
I am currently trying to update my own little personal weight tracker using Firebase and React Native. However, whenever I log DataSnapshot.val()
I receive the input 22
, which is perfect. But when I return the very same value I receive Undefined
.
I tried both get()
and onValue()
with the same results. The path is correct, since I get the correct data using console.log.
https://firebase.google.com/docs/database/web/read-and-write?authuser=2
I tried following the above documentation. But is it updated? snapshot
is currently DataSnapshot
?
Firebase:
const readWeight = (database, userId) => {
get(ref(database, `users/${userId}/weight`)).then((DataSnapshot) => {
try {
if (DataSnapshot.exists()) {
console.log(
`Weight found. Current weight is: ${DataSnapshot.val()} kg`
);
return DataSnapshot.val();
} else {
console.log("Weight wasn't found");
}
} catch (error) {
console.log(error);
}
});
};
HomeScreen.js
// Modules
import { react, useState, useEffect } from "react";
import { Text, TouchableOpacity, View, TextInput, Image } from "react-native";
import { LogOutButton } from "../Components/LogOutButton";
import { auth, writeUserData, database, readWeight } from "../firebase";
// Stylesheet
import { styles } from "../Stylesheet/Stylesheet";
export const HomeScreen = () => {
const user = auth.currentUser;
let currentUserWeight = readWeight(database, user.uid);
console.log("Current Weight: ", currentUserWeight);
return (
<View style={styles.profileMain}>
<View style={styles.profileInfoContainer}>
<View style={styles.HOME__profileWeightContainer}>
<Text style={styles.HOME__profileWeightText}>
Last Weight: {currentUserWeight}
</Text>
</View>
</View>
</View>
</View>
);
};