-
-
Save amanshu-kataria/0d4bcbdbbac57abdd1ef2d2505042c5f to your computer and use it in GitHub Desktop.
Replacing 'componentWillReceiveProps' with 'getDerivedStateFromProps'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {PureComponent} from "react"; | |
import DisplayStat from "./displayStat.js" | |
class App extends PureComponent{ | |
constructor(){ | |
super(); | |
this.state={ | |
path : "path-1" | |
} | |
} | |
changePath=()=>{ | |
this.setState({path: "path-2"}); | |
} | |
render(){ | |
return( | |
<div> | |
<DisplayStat path={this.state.path} /> | |
<div onClick={this.changePath} >Change Path</div> | |
</div> | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {PureComponent} from "react"; | |
class DisplayStat extends PureComponent{ | |
constructor(props){ | |
super(); | |
this.state={ | |
firebaseRef: firebase.database().ref(this.props.path); | |
} | |
} | |
componentDidMount() { | |
this.getData(this.state.firebaseRef); | |
} | |
componentWillReceiveProps(nextProps){ | |
if(nextProps.path!==this.props.path){ | |
let {firebaseRef}=this.state; | |
firebaseRef.off("value"); //Turn off the connection to previous path. | |
firebaseRef=firebase.database().ref(nextProps.path); | |
this.setState({firebaseRef, path :nextProps.path }); | |
this.getData(firebaseRef); | |
} | |
} | |
getData=(ref)=>{ | |
// open connection and listen to firebase path | |
ref.on("value", snapshot => { | |
//Perform some operation | |
}); | |
} | |
render(){ | |
return( | |
<div> | |
//Display Stats | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment