Created
October 16, 2019 18:53
-
-
Save dsafreno/c92db671c930bc2bf326284efe83655d to your computer and use it in GitHub Desktop.
Firebase RTDB Component, before withDbData
This file contains hidden or 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
class Example extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { user: null, team: null }; | |
} | |
componentDidMount() { | |
let {userId, teamId} = this.props; | |
// subscribe to user data | |
let userRef = firebase.database().ref(`users/${userId}`); | |
let userOff = userRef.on('value', (snap) => { | |
this.setState({user: snap.val()}); | |
} | |
this.userOff = () => ref.off('value', userOff); | |
// subscribe to team data | |
let teamRef = firebase.database().ref(`teams/${teamId}`); | |
let teamOff = teamRef.on('value', (snap) => { | |
this.setState({team: snap.val()}); | |
} | |
this.teamOff = () => ref.off('value', teamOff); | |
} | |
componentDidUpdate(prevProps, prevState) { | |
if (!prevState.user && this.state.user) { | |
// first time we got user data! | |
} | |
if (!prevState.team && this.state.team) { | |
// first time we got team data! | |
} | |
} | |
componentWillUnmount() { | |
this.userOff(); | |
this.teamOff(); | |
} | |
render() { | |
let { user, team } = this.state; | |
if (!user || !team) { | |
return null; | |
} | |
// ... | |
} | |
} | |
export default Example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment