logaretm / villus

🏎 A tiny and fast GraphQL client for Vue.js

Home Page:https://villus.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using useQuery() from instead a function in setup

ShadeProps opened this issue · comments

I'm trying to trigger a function call from the template but when I wrap useQuery() in a function, it loses access to the instance.

The code below fails because useQuery calls getCurrentInstance and it returns null when called from instead a function

Is there a solution to using Villus from inside a function?

Context: I am using Vitesse

<template>
        <button
          @click="test"
        >
          Test
        </button>
</template>
setup() {
    const test = async() => {
      const { data } = await useQuery({
        query: gql`
                query Status {
                  status {
                    status
                  }
                }
              `,
      })
    }

    return { test }
}

Linusborg on the Vue Land discord pointed this out to me

"The docs say that you can 1) disable the automatic fetch on mount with an option called fetchOnMount:false and 2) manually trigger a query with the execute() function retuned by useQuery()."

I was able to resolve this with the following code

const { execute } = useQuery({
  query: gql`
            query Status {
              status {
                status
              }
            }
          `,
  fetchOnMount: false,
})
const test = async() => {
  const { data } = await execute()
}