这就是我的简单函数同步数据的方式:
功能
import { getData } from './api/index'
export default async function synchronize (navigator) {
const data = await getData()
// ... then store data to local db...
}
我正在使用RESTful API从服务器获取一些数据:
的getData
import { Alert, AsyncStorage } from 'react-native'
async function getData () {
try {
const lastSynched = await AsyncStorage.getItem('data.lastSynched')
const date = lastSynched ? Number(Date.parse(lastSynched)) / 1000 : 0
const token = await AsyncStorage.getItem('auth.token')
const uriBase = 'http://localhost:3000'
let response = await fetch(`${uriBase}/get-data/${date}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-access-token': token
}
})
let responseJson = await response.json()
return responseJson
} catch (error) {
Alert.alert('Error', 'Could not synchronize data')
}
}
export default getData
但是现在我正在使用apollo graphQL,我不明白如何使用查询来获取数据,因为我在这里使用了一个函数(synchronize()) - 而不是组件。
答案 0 :(得分:0)
我认为良好的开端将来自link。这里有很好的例子,说明如何使用Apollo客户端执行查询和获取数据。
也许我不能正确理解问题是什么,但这里有很高的阿波罗使用率。
首先,您需要创建Apollo客户端,并至少为GraphQL端点提供URI。
import ApolloClient from "apollo-boost";
const client = new ApolloClient({
uri: "https://w5xlvm3vzz.lp.gql.zone/graphql"
});
创建客户端后,您应该使用以前创建的客户端执行查询,如下所示:
import gql from "graphql-tag";
client
.query({
query: gql`
{
rates(currency: "USD") {
currency
}
}
`
})
.then(result => console.log(result));
确保您已安装apollo-boost react-apollo graphql-tag graphql
个软件包。还要确保将查询包装成这样的GraphQL标记,因为它会编译您的查询。