Skip to content

Instantly share code, notes, and snippets.

@amanshu-kataria
Created May 14, 2018 09:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amanshu-kataria/9a70ba6ef48611b2fc19f81c718c695e to your computer and use it in GitHub Desktop.
Save amanshu-kataria/9a70ba6ef48611b2fc19f81c718c695e to your computer and use it in GitHub Desktop.
Replacing getDerivedStateFromProps example
import React, {PureComponent} from "react";
class DisplayStat extends PureComponent{
constructor(props){
super();
this.state={
path: this.props.path,
firebaseRef: firebase.database().ref(this.props.path);
}
}
componentDidMount() {
this.getData(this.state.firebaseRef);
}
componentDidUpdate(prevProps, prevState) {
if (prevState.path !== this.state.path) {
let firebaseRef=firebase.database().ref(this.state.path);
this.setState({firebaseRef});
this.getData(firebaseRef);
}
}
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.path!==prevState.path){
let firebaseRef=prevState.firebaseRef;
firebaseRef.off("value"); //Turn off the connection to previous path.
// We can't do this here as we can't access `this` inside this method.
// firebaseRef=firebase.database().ref(nextProps.path);
// this.setState({firebaseRef, path :nextProps.path });
// this.getData(firebaseRef);
return {path : nextProps.path};
}
else return null;
}
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