Skip to content

Instantly share code, notes, and snippets.

@amanshu-kataria
Last active May 14, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amanshu-kataria/0d4bcbdbbac57abdd1ef2d2505042c5f to your computer and use it in GitHub Desktop.
Save amanshu-kataria/0d4bcbdbbac57abdd1ef2d2505042c5f to your computer and use it in GitHub Desktop.
Replacing 'componentWillReceiveProps' with 'getDerivedStateFromProps'
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>
)
}
}
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