Ad

Cannot Read Proper Query In GraphQL Apollo Client

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?

Ad

Answer

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-onlyfetchPolicy. https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy

Ad
source: stackoverflow.com
Ad