apollo
apollo copied to clipboard
Using vue-apollo-composable inside a Pinia setup store
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",
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,
};
});
See a working example here that is passing in our automated tests.
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.