Ivo Ivo - 19 days ago 9
React JSX Question

How to get data out of a Promise in React/Firebase?

This is the promise within a render() method of a React component.

firebaseRef.child("users/" + auth.uid).once('value').then((snapshot) => {
let userName = snapshot.val().name;
});


I want to get the data of snapshot.val().name and put it in the

return(
<h1>{userName}</h1>
)


I could get the data out of the promise with an action dispatch to the redux store and then retrieving it where I need it but there should be a shorter way of achieving it I suppose? I tried different ways to do so but I failed due to the asynchronicity so... please help!

Answer

I was going to upvote the previous comment, but he failed to mention that doing this inside of the render method is a bad idea. That would make an infinite loop. Render -> promise resolves -> set state -> render -> repeat. You should do your firebase promise like this:

class Test extends React.Component{
  constructor() {
    super()
    this.state = {}
  }

  componentDidMount() {
    let { auth } = this.props //or wherever it comes from

    firebaseRef.child("users/" + auth.uid).once('value').then((snapshot) => {
      this.setState({ userName: snapshot.val().name });
   });
  }

  render() { 
    let { userName } = this.state
    return (
      <h1>{userName}</h1>
    )
  }
}