Search code examples
vuejs2apolloapollo-clientvue-apolloneo4j-graphql-js

Does Vue Apollo saves queries in cache?


I am currently trying to force Vue Apollo to query the latest data on an event. However, when the apollo query re-query on an event (i.e. on route change) it still loads old results (although the data had changed in the meanwhile). Only when I refresh/reload the webpage the query is fetching correctly and the newest data appears. Is it because the previous query results are saved in the cache? And if so, how do I pass options in my query: I read in the documentation that you can pass an option fetchPolicy: no-cache (see https://v4.apollo.vuejs.org/api/use-query.html#parameters). Where do I pass this option in my query? I have my query in dedicated files, for example my query is in a separated get_questionnaire.gql file like:

query ($username: String!, $id: ID!){
    users(where: { username: $username }) {
        Questionnaire(where: { id: $id }) {
            OpenQuestions
            ClosedQuestions
        }
    }
}

And I call it from my application:

  import GetQuestionnaire from './graphql/get_questionnaire.gql';

  await this.$apollo.query({
    query: GetQuestionnaire,
    variables: {
      username: "Kilian",
      id: "Project 1"
    }
  }).then((data) => {
    ...
  }

Where do I define my options here? I tried the following but it doesn't work:

  import GetQuestionnaire from './graphql/get_questionnaire.gql';

  await this.$apollo.query({
    query: GetQuestionnaire,
    variables: {
      username: "Kilian",
      id: "Project 1"
    },
    options: {'fetchPolicy': 'network-only'} // I added this line
  }).then((data) => {
    ...
  }

So, would this "not caching" solve my problem? My main goal is to re-run my queries once my application has rendered but at the moment the responses are still showing me old data (although the data has changed in the meanwhile).

Many thanks for your help and ideas.


Solution

  • Indeed, Apollo saves queries as default in the cache. That is why a second query will response the previous cached response. My approach above is almost correct:

     import GetQuestionnaire from './graphql/get_questionnaire.gql';
    
      await this.$apollo.query({
        query: GetQuestionnaire,
        variables: {
          username: "Kilian",
          id: "Project 1"
        },
        options: {'fetchPolicy': 'network-only'} // this was wrong
      }).then((data) => {
        ...
      }
    

    The correct way would be:

      import GetQuestionnaire from './graphql/get_questionnaire.gql';
    
      await this.$apollo.query({
        query: GetQuestionnaire,
        variables: {
          username: "Kilian",
          id: "Project 1"
        },
        fetchPolicy: 'network-only' // I changed this line
      }).then((data) => {
        ...
      }