0

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>
  );
};
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • `readWeight` has no `return` statement – Quentin Mar 09 '22 at 11:37
  • Thanks for the quick input. I tried return, but it still returns "undefined" sadly. ```const readWeight = async (database, userId) => { const DataSnapshot = await get(ref(database, `users/${userId}/weight`)); const weightVal = DataSnapshot.val(); console.log(`Weight found. Current weight is: ${weightVal} kg`); return weightVal; };``` – Stefan Andersen Mar 09 '22 at 12:49

0 Answers0