Skip to content

Instantly share code, notes, and snippets.

@AniketSK
Created June 30, 2019 14:13
Show Gist options
  • Save AniketSK/24661be88a5cbbe25da347b766f1982b to your computer and use it in GitHub Desktop.
Save AniketSK/24661be88a5cbbe25da347b766f1982b to your computer and use it in GitHub Desktop.
A higher order component to abstract away the connection to Firebase.
import React from 'react';
import firebase from 'firebase/app';
import { FormValidation } from '../../constants';
class Document extends React.Component {
constructor(props) {
super(props);
this.db = firebase.firestore();
this.db.settings({ timestampsInSnapshots: true });
this.willSubscribe = this.props.path != null;
this.state = {
snapShot: [],
};
}
componentDidMount() {
if (this.willSubscribe) {
this.unsubscribe = this.db // begins a subscription to this collection for live updates https://firebase.google.com/docs/firestore/query-data/listen
.collection(this.props.path)
.where(FormValidation.VETTED, '==', this.props.vetted) // There's a Route based mechanism to choose whether to show vetted or unvetted talks. Vetted ones only by default.
.onSnapshot(snapShot => this.setState({ snapShot }));
}
}
componentWillUnmount() {
this.setState({ snapShot: [] });
this.willSubscribe && this.unsubscribe(); // release the subscription to the data if it had one
}
render() {
return (
<React.Fragment>
{this.props.children({ db: this.db, snapShot: this.state.snapShot })}
</React.Fragment>
);
}
}
export default Document;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment