Giggioz
Giggioz

Reputation: 477

Using Apollo Client Query to fetch data from an asynchronous library

I've just finished to read through the tutorial in the Apollo GraphQL web page and I'm (obviously?) dazed :)

I'm here because in my use case I have a client library (which I wrote, let's call it InnerClient) that exposes some methods that make grapqhl calls internally, it has no UI.

Now I wanted to import this library in an react apollo project (ApolloReactClient) and i wanted to understand how to leverage the Apollo Client superpowers in this case: i don't have any queries o mutations to do explicitly, I want to call my InnerClient methods, wait for the response (they are asynchronous of course) and then render my React Components in the ApolloReactClient, using the convenient properties that the Query component returns (like data, loading, error...)

I read something about Links and maybe this is the right way to do so but I'm not sure at all.

Can you help me to address me on this issue? Could you provide a small example in which you have a React component wrapped by the (Apollo) Query component that fetches data from an internal library as in my case?

Regards

Upvotes: 0

Views: 3170

Answers (1)

Giggioz
Giggioz

Reputation: 477

I think this is the way to do it

https://github.com/apollographql/apollo-link-state/tree/master/examples/async

Edit (adding more info): Basically it is possibile with apollo-link-state, it allows to combine your client state with resolvers that work with mutations and queries especially designed for it with the @client directive.

 const client = new ApolloClient({
  link: withClientState({ resolvers }),
  cache: new InMemoryCache(),
 });

Here you say Apollo to use for the requests resolvers and passing to them the client state.

const GET_CURRENT_POSITION = gql`
 query getCurrentPosition($timeout: Int) {
  currentPosition(timeout: $timeout) @client {
  coords {
    latitude
    longitude
  }
}

} `;

Here you define a query for the client (note @client) and the query is resolved in an asynchronous way with this promise

   const getCurrentPosition = options => {
    return new Promise((resolve, reject) => {
     navigator.geolocation.getCurrentPosition(resolve, reject, options);
    });
   };

Hope this helps!

Upvotes: 2

Related Questions