1

On one of my pages in my app I'm doing two api calls with graphql apollo client. One is document, the other one menu. I need menu data in one of my components so I want to use readQuery in order to not to fetch it again. What I'm doing is:

const client = useApolloClient();

  try {
const testData = client.readQuery({
  query: gql`
  query ($result: String) {
    menu(result:  $result) {
      text
    }
  }
`,
  variables: {
    result: „testresult”
  },
});
console.log(testData);
} catch(e) {
  console.log(e);
}

What graphQL is doing is looking for document root query so the error looks like this:

Invariant Violation: Can't find field menu({"lang":"en-us"}) on object 

{
  "document({\"lanf\":\"en-us\",\"id\":\"mySite\"})": {
    "type": "id",
    "generated": false,
    "id": "XO5tyxAAALGzcYGG",
    "typename": "Document"
  }
}.

I believe that it is because menu data is not there yet.

How can I wait until it will be there?

Murakami
  • 3,474
  • 7
  • 35
  • 89

1 Answers1

1

You are right. You are getting an error because the data is not in cache yet:

The query method, on the other hand, may send a request to your server if the appropriate data is not in your cache whereas readQuery will throw an error if the data is not in your cache. readQuery will always read from the cache.

https://www.apollographql.com/docs/react/advanced/caching/#readquery

To do what you want use the a normal query with a cache-only fetchPolicy. https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy

Johnny Zabala
  • 2,285
  • 1
  • 12
  • 14
  • But wouldn’t that throw an error as well? From docs: If the data for your query does not exist in the cache then an error will be thrown – Murakami Jun 08 '19 at 06:23
  • So I guess `cache-first` will be more appropriate here. Thanks for helping and putting on the right track – Murakami Jun 08 '19 at 08:39
  • 1
    No, it won't throw an error. When you use useQuery, if there is not data, that is all. You have to handle the no data case in the ui. The `fetchPolicy` `cache-first` is the default behavior. Apollo will look into the cache and if there is not data it will make a request. Otherwise not. So, to use `cache-first` just use useQuery like you normally do. – Johnny Zabala Jun 08 '19 at 16:31