Reputation: 17362
This is how my simple function to synchronize the data looks like:
Function
import { getData } from './api/index'
export default async function synchronize (navigator) {
const data = await getData()
// ... then store data to local db...
}
I'm fetching some data from the server using an 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
But now I'm using apollo graphQL and I do not understand how to get the data using a query as I'm using here a function (synchronize()) - not a component.
Upvotes: 1
Views: 480
Reputation: 5332
I think good start will be from this link. Here you have good examples how to use Apollo client to execute query and fetch data.
Maybe I don't understand properly what is issue but here is high level of Apollo usage.
First you will need to create Apollo client and supply at least URI to GraphQL endpoint.
import ApolloClient from "apollo-boost";
const client = new ApolloClient({
uri: "https://w5xlvm3vzz.lp.gql.zone/graphql"
});
Once you created client you should than execute your query with previously created client like in following:
import gql from "graphql-tag";
client
.query({
query: gql`
{
rates(currency: "USD") {
currency
}
}
`
})
.then(result => console.log(result));
Make sure that you installed apollo-boost react-apollo graphql-tag graphql
packages. Also make sure that you wrap your query into GraphQL tag like this because it will compile your query.
Upvotes: 1