Search code examples
vue.jsgraphqlvuejs3apollo

Vue 3, GraphQL, Apollo - How to re-render query when cache changes?


I would like to know how to build Vue 3 Apollo apps with queries and mutations. I'm familiar with react useQuery hook. It re-renders the component whenever the cached data has been changed (by mutations).

I have tried:

In all cases it just loads the data once and doesnt react to cache data changes.

I undestand that I can build own setup by Apollo client or refetch the queries. I can even invalidate components by its keys. This is not really as elegant as the React useQuery hook is.

I was curious whether there is any ready-made solution and the best practice for smooth graphql operations in Vue 3.


Solution

  • I have misconfigured the schema and cache update. So the answer is that it works well.

    For example:

    <template>
      <div v-if="loading">...loading</div>
      <div v-else-if="error">{{ error.message }}</div>
      <div v-else>{{value}}</div>
    </template>
    
    <script setup lang="ts">
      import gql from "graphql-tag";
      import { GetValueQuery } from "./ValueComponent.generated";
      import { useQuery, useResult } from "@vue/apollo-composable";
    
      const GetValue = gql`
        query getValue {
          value
        }
      `;
    
      function useGetValue() {
        const { result, loading, error } =
          useQuery<GetValueQuery>(GetValue);
        const value = useResult(result, null, (data) => data.value);
        return { value, loading, error };
      }
    
      const { value, loading, error } = useGetScans();
    </script>
    
    

    Works the described way - the template is re-rendered once data cache changed (by a mutation with the proper result set or by its update function)

    So it is not valid question, the bug was in the implementation of cache policy on my side.