vuejs / apollo

🚀 Apollo/GraphQL integration for VueJS
http://apollo.vuejs.org
MIT License
6.01k stars 521 forks source link

Using vue-apollo-composable inside a Pinia setup store #1527

Open bipsen opened 8 months ago

bipsen commented 8 months ago

I expect to be able to make queries inside a pinia setup store as per https://github.com/vuejs/apollo/issues/1505.

When I run the code below, however, result stays undefined. I can see from the watchEffect log that the query runs and gets the correct response, so why doesn't result seem to be reactive in my component?

// stores/campers.ts
import SOME_QUERY from "@/gql/queries/SOME_QUERY.gql";

export const useCamperStore = defineStore("campers", () => {
  const { data: authData } = useAuth();

  const camperQueryVariables = computed(() => {
    return {
      id: authData.value?.id,
    };
  });

  const { result, refetch } = useQuery(SOME_QUERY, camperQueryVariables);

  watchEffect(() => console.log(result.value));

  return {
    result,
    refetch,
    camperQueryVariables,
  };
});
//SomeComponent.ts
<template>
  <div>
    <!-- This is undefined -->
    result: {{ result }} 

    <!-- This works as expected -->
    camperQueryVariables: {{ camperQueryVariables }}
  </div>
</template>

<script lang="ts" setup>
import { useCamperStore } from "@/stores/campers";
const { result, camperQueryVariables } = useCamperStore();
</script>

Versions "vue": "^3.3.4", "nuxt": "^3.7.4", "@nuxtjs/apollo": "^5.0.0-alpha.7", "@vue/apollo-composable": "^4.0.0-beta.11", "@apollo/client": "^3.8.7",

bipsen commented 8 months ago

My best solution so far has been to use a reactive object with onResult. Is that best solution to this problem?

// stores/campers.ts
import SOME_QUERY from "@/gql/queries/SOME_QUERY.gql";

export const useCamperStore = defineStore("campers", () => {
  const result = reactive({ data: null });

  const { data: authData } = useAuth();

  const camperQueryVariables = computed(() => {
    return {
      id: authData.value?.id,
    };
  });

  const { onResult, refetch } = useQuery(SOME_QUERY, camperQueryVariables);

  onResult((queryResult) => {
    result.data = queryResult.data;
  });

  return {
    result,
    refetch,
  };
});
Akryum commented 8 months ago

See a working example here that is passing in our automated tests.

dash- commented 1 month ago

I don't have issues with simple implementations like what is passing in that automated test. I do run into issues when there is one or more query variable that changes, particularly when paired with vue-router navigations.