Created
May 11, 2018 08:06
-
-
Save kitze/bbcdbb219d1eea4de7ad322be88680db to your computer and use it in GitHub Desktop.
Apollo data fetching component for react-native
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 {NetworkStatus} from 'apollo-client'; | |
import get from 'lodash/get'; | |
import React, {Component} from 'react'; | |
import {Query} from 'react-apollo'; | |
class Data extends Component { | |
state = {refreshing: false}; | |
onRefresh = refetch => { | |
this.setState({refreshing: true}, () => { | |
refetch().then(() => { | |
this.setState({refreshing: false}); | |
}); | |
}); | |
}; | |
render() { | |
const {children, variables, query, dataPath, process} = this.props; | |
const {refreshing} = this.state; | |
return ( | |
<Query | |
fetchPolicy="cache-and-network" | |
variables={variables} | |
query={query}> | |
{result => { | |
const {data, refetch, loading, networkStatus} = result; | |
const foundData = get(data, dataPath); | |
const statusIsRefresh = networkStatus === NetworkStatus.refetch; | |
return children({ | |
onRefresh: () => this.onRefresh(refetch), | |
refreshing, | |
loading, | |
loadingSpinner: !foundData && loading && statusIsRefresh === false, | |
data: foundData ? (process ? process(foundData) : foundData) : null | |
}); | |
}} | |
</Query> | |
); | |
} | |
} | |
export default Data; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment