javascript - Firebase in react's componentWillMount -


so i'm making firebase + reactjs app, , need check if element exists before components mount, , set state's existing property based on that.

the problem need use

componentwillmount() {         let newstate = {}         firebase.database()             .ref(`/refs/${this.props.match.params.channel}`)             .once('value', val => val.val())             .then(value => {                 let val = value.val()                 if (val) {                     let dbref = val.ref                     newstate = {                         dbref,                         exists: true                     }                 } else {                     newstate.exists = false                 }                 this.setstate(newstate)             })     }      componentdidmount() {             if(this.state.exists) {                 console.log(`/channels/${this.state.dbref}/messages`)                 firebase.database()                     .ref(`/channels/${this.state.dbref}/messages`)                     .on('value', snap => {                         const snapshot = snap.val()                         let messages = []                         if (snapshot) {                             object.keys(snapshot).foreach(k => messages.push(snapshot[k]))                         }                         this.setstate({ messages })                         this.refs.messages.scrolltop = this.refs.messages.scrollheight                     })     } } 

which async, time need access property in componentdidmount firebase query might not have been resolved yet. ideas on how fix it? possible use await in component's functions?

thanks in advance!


Comments

Popular posts from this blog

python - Alternative to referencing variable before assignment -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -