简体   繁体   中英

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!

I haven't done React in a while, but I think it's:

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

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>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM