Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created April 3, 2018 23:57
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 ryanflorence/81b67104057a1a536c1e822e2be5b9c9 to your computer and use it in GitHub Desktop.
Save ryanflorence/81b67104057a1a536c1e822e2be5b9c9 to your computer and use it in GitHub Desktop.
import { db } from "./firebase";
import { Component } from "react";
const cache = {};
class Doc extends Component {
static propTypes = {
path: () => {}
};
unsubscribe = () => {};
state = {
doc: cache[this.props.path] || null,
loading: cache[this.props.path] ? false : true
};
componentDidMount() {
this.subscribe();
}
componentDidUpdate(prevProps) {
if (prevProps.path !== this.props.path) {
this.unsubscribe();
this.subscribe();
this.setState({ loading: true });
}
}
componentWillUnmount() {
console.log("unmounting", this.props);
this.unmounted = true;
}
subscribe() {
const { path } = this.props;
let ref = db.doc(path);
this.unsubscribe = ref.onSnapshot(snapshot => {
const doc = { ...snapshot.data(), id: snapshot.id };
cache[path] = doc;
if (!this.unmounted) {
this.setState({
doc: doc,
loading: false
});
} else {
console.log("long gone sucker, collect dat garbage", this.props);
}
});
}
render() {
return this.props.children(this.state);
}
}
export default Doc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment