reactjs - In ReactFire, how to bind a ref that depends on a property? -


i have react component used <username uid={uid}>, in i'd use value of firebase reference depends on uid. since props can change, looks need bind reference in both componentwillmount , componentwillreceiveprops like:

componentwillmount() {   this.bindasobject(userroot.child(this.props.uid).child('name'), 'username'); },  componentwillreceiveprops(nextprops) {   this.unbind('username');   this.bindasobject(userroot.child(this.props.uid).child('name'), 'username'); },  render() {   return <span>{this.state.username['.value']}</span>; }, 

the react documentation warns against having state depend on props, presumably avoid need update state 2 places.

is there better way this?

this looks fine. anticipating uid change , reacting it.

some improvements consider:

adding uid equality check rebind if uid changes

if need access other user properties, create single containing component binds entire user data object , passes down data props:

componentwillmount() {   this.bindasobject(userroot.child(this.props.uid), 'user'); },  componentwillreceiveprops(nextprops) {   if (this.props.uid !== nextprops.uid) {     this.unbind('user');     this.bindasobject(userroot.child(this.props.uid), 'user');   } },  render() {   return (     <div>       <username name={this.state.user.name}></username>       <gravatar email={this.state.user.email}></gravatar>     </div>   ); }, 

ideally want fetching/listening code in 1 component lower level components don't need care how data fetched.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -