Last active
May 30, 2018 00:45
-
-
Save dburles/253a25366365232298d34b03b13f316f to your computer and use it in GitHub Desktop.
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
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