Skip to content

Instantly share code, notes, and snippets.

@dburles
Last active May 30, 2018 00:45
Show Gist options
  • Save dburles/253a25366365232298d34b03b13f316f to your computer and use it in GitHub Desktop.
Save dburles/253a25366365232298d34b03b13f316f to your computer and use it in GitHub Desktop.
import React from 'react';
export default class Query extends React.Component {
state = {
loading: true,
data: {},
};
static defaultProps = {
skip: false,
variables: null,
};
fetch = () => {
this.setState(() => ({ loading: true }));
this.props.query
.fetch({ variables: this.props.variables })
.then(({ data }) => {
this.setState({
loading: false,
data,
});
});
};
componentDidMount() {
if (!this.props.skip) {
this.subscription = this.props.query.subscribe(this.fetch);
this.fetch();
}
}
componentWillUnmount() {
// XXX: stop inflight request somehow?
if (this.subscription) {
this.subscription();
}
}
render() {
if (this.props.skip) {
return this.props.children;
}
const props = {
loading: this.state.loading,
data: this.state.data,
refetch: this.props.query.refetch,
fetchMore: this.props.query.fetchMore,
rerender: this.rerender,
...this.props,
};
return this.props.children(props);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment