Can not access data of useQuery result - _rawValue - Uncaught (in promise) ReferenceError | Vue 3 Apollo 4

422 views Asked by At

I'm trying a simple API request with Vue 3 and Apollo 4 with the composition API. I want to get the backend data into a pinia store, so I have the API call in the store under actions {}. Then I want to process the data in the same function.

The backend shows the correct request and vue receives the correct data in the result._rawValue, but I can't access it while code execution.

store.js:

import { defineStore } from "pinia"
import { useQuery } from '@vue/apollo-composable'
import { ALL_BLOGS } from "@/queries";

export const useBlogStore = defineStore({
  id: "BlogStore",
  state: () => ({
    blog_api: [],
  }),
  actions: {
    getAllBlogs() {
        const { result } = useQuery(ALL_BLOGS)
        console.log('store test')
        console.log(result) // returns Ref
        console.log('store test end')

        this.blog_api = result.allBlogs.map(item => item.name) // process data
    },
  },

});

Fetching data only in a component does also not work. Just fetch and process the data, without using the store. component.vue

<template>
<v-container>
  <v-row>
    <!-- does not work -->
    {{ blogs }}
  </v-row>
  <v-row>
    <!-- does work -->
    {{ result.allBlogs.map(item => item.name) }}
  </v-row>
</v-container>
</template>
<script setup>
import { useBlogStore } from "@/store/store"
import { useQuery } from '@vue/apollo-composable'
import { computed } from "vue"
import { ALL_BLOGS } from "@/queries"

const BlogStore = useBlogStore();

const { result } = useQuery(ALL_BLOGS);
const blogs = computed(() => result.allBlogs.map(item => item.name));

</script>

From what I understand, the useQuery result is a ref and when I want to access the result, it is not yet there. When I add async ... await before the useQuery, the editor tells me, useQuery is already an asynchronous function and await has no effect here. Couldn't work it out with computed, watchers or .then

Not that good with JavaScript, some help would be nice. Do I have to wait for useQuery to finish the request or for the Ref variable to update properly? And how would I do that?

1

There are 1 answers

1
Thomas On

So my JavaScript knowledge is just too poor I guess. This does work:

const blogs = computed(() => result.value?.allBlogs.map(item => item.name) ?? []);

And this does not:

const blogs = computed(() => result.allBlogs.map(item => item.name));

Can someone tell me what the difference is? Why can I use the second in the template, but not in the setup and why is the first ok to use in the setup?