Cannot further process the result from useQuery in Vue Apollo (Vue 3, composition API)

805 Views Asked by At

I have a Vue 3 component that displays some data, fetched through a composable that talks to an API via Apollo. The useMyQuery function returns result and loading from the query, which works fine. It also does a transformation (transformData) on an array from the result object (arrayData). This is the part that doesn't work.

When I run the code as displayed, I get the error Uncaught (in promise) TypeError: data is undefined (I assume because when it first runs, useQuery hasn't returned anything yet. But if I wrap the content of the transformData-function like if (!data) {return null} else {...}, it never seems to update, it just returns null.

I wonder if this is because I am running the function only on the result.arrayData, which is not reactive? In that case, how can I make this work?

The composable:

// useMyQueries.js
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

export function useMyQuery() {
    const variables = {
        'search': "hello",
        'limit': 0
    }
    const { result, loading } = useQuery(gql(QUERY), variables)

    function transformData(data) {
        return {
            labels: data.map(item => item.time),
            datasets: [{ data: data.map(item => item.count) }]
        };

    }
    return {
        result,
        loading,
        transformedData: transformData(result.arrayData),
    }
}

The component:

// MyComponent.vue
<template>
    <v-container>
        <v-card title="Title" :loading="loading">
            <v-card-text>
                {{ transformedData }}
            </v-card-text>
        </v-card>
    </v-container>
</template>

<script setup>
import { useMyQuery } from '@/useMyQueries.js'

const { result, loading, transformedData } = useMyQuery()

</script>
0

There are 0 best solutions below