-
-
Save amanshu-kataria/9a70ba6ef48611b2fc19f81c718c695e to your computer and use it in GitHub Desktop.
Replacing getDerivedStateFromProps example
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={ | |
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