apollo: Cannot query on button click? (in v4 composition API)

Thanks for the library and effort given.

Similar to #121, I need an example how to query after an event (such as button click) in v4 composition API?

Further info: I’m using vue-apollo with Nuxt. (Not @nuxtjs/apollo, because it doesn’t support vue-apollo v4 yet.)

I tried below methods:

setup(props, context) {
  const enabled = ref(false)
  const q1 = useQuery(someQuery); // This is OK.

  // When I add below line, browser hangs during page load and waits forever.
  const q2 = useQuery(someQuery, null, { enabled: enabled.value });

  // Click handler throws when executed on click event.
  // Cannot read property '$isServer' of null at useQuery (useQuery.js?a2fd:25)
  function onClick() {
    const q3 = useQuery(someQuery);
  }
}

Many thanks,

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 10
  • Comments: 22 (5 by maintainers)

Most upvoted comments

Hello @mtsmachado8 i’ve found a working solution.

const queryOptions = ref({
  // whatever options you need
  enabled: false
})

const {result} = useQuery(<query>, <variables>,queryOptions)

// Do with the result what you need

const onClick = () => {
  queryOptions.value.enabled = true
}

This works for me and queries only once, when the Button is clicked. For me, instead of only doing the enabled as a ref, using the whole options-obejct as a ref did the trick.After that, if you want to requery on every click, you can use the refetch-Option from the useQuery like

const {result, refetch} = useQuery(<query>, <variables>,queryOptions)

const onClick = () => {
  if (!queryOptions.value.enabled) {
    queryOptions.value.enabled = true
    return 
  }
  refetch()
}

I hope this helps!

This seems very inelegant. Executing a query on click (or whatever event) should work as expected imo.

The right way to do it is not to use useQuery neither useLazyQuery but instead useApolloClient like this:

import { useApolloClient } from '@vue/apollo-composable'

const { client } = useApolloClient()

const onClick = async () => {
  const { data } = await client.query({
    query: someQuery,
    variables: someVariablesIfNeeded,
  })
}

Thankss @aaronschweig, it really helped!!!