0

i want to call a getName function which takes a game.set(Integer) and returns a String. This string i want to set inside the text element. The function is working perfectly, I printed the results before returning. Now, after importing the function import { getName } from '../SetsAPI';, the result I get after calling the function is always undefined.

Function call:

import { getName } from '../SetsAPI';
...
    <View style={styles.row}>
      <Text style={styles.text}>Game: </Text>
          <View style={styles.questionAmount}>
               <Text>{getName(game.set)}</Text>
          </View>
     </View>

Function:

 export const getName = (setId)=>{
    console.log("setId: " + setId)
    setsRef
    .doc(setId)
    .get()
    .then((doc) => {
      if (doc.exists) {
        console.log("document name: " + doc.data().name)
        return doc.data().name;
      } else {
        console.log("No such document!");
      }
  })
  }

Why does this happen? And how can I prevent it? Thank you!

Grrrrrag
  • 47
  • 7

1 Answers1

2

You'll want to use useState to store the value, which then causes it to be updated in the UI.

First declare the state at:

{name, setName} = useState('');

This allows us to get name and call setName, and gives it an initial value of ''.

Then in your componentDidMount or in a useEffect hook, you'll do:

setsRef
.doc(setId)
.get()
.then((doc) => {
  if (doc.exists) {
    console.log("document name: " + doc.data().name)
    setName(doc.data().name);
  } else {
    console.log("No such document!");
  }

This causes your component to rerender itself, and then you can use the name property in your render method.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807