urql icon indicating copy to clipboard operation
urql copied to clipboard

[@urql/vue] Cannot use useQuery inside of vue-router guard

Open leonidk101 opened this issue 1 year ago • 3 comments

Describe the bug

The setup: There's a pinia store that is used in a router guard, the store uses useQuery composable from @urql/vue

Because it tried to access vue instance in router guard the app returns the following error:

use* functions may only be called during the `setup()` or other lifecycle hooks.

As far as I can see the error comes from https://github.com/urql-graphql/urql/blob/25d114d25807f0676dbf453732602753279ba0db/packages/vue-urql/src/useClient.ts#L104

Am I doing something wrong?

Reproduction

https://stackblitz.com/edit/vitejs-vite-kudyigng

Urql version

@urql/vue v1.4.2

Validations

  • [X] I can confirm that this is a bug report, and not a feature request, RFC, question, or discussion, for which GitHub Discussions should be used
  • [X] Read the docs.
  • [X] Follow our Code of Conduct

leonidk101 avatar Jan 06 '25 23:01 leonidk101

I encountered this issue when trying to use useQuery in a composable. Maybe I'm missing something too. Otherwise, it seems to me that it would contradict Composition API pattern.

Could you use useClientHandle instead? This one works outside components, but it is intended for one shot queries...

arkandias avatar Feb 20 '25 23:02 arkandias

This is due to the use of getCurrentInstance as vue router isnt a component instance.

If urql-vue bumps its vue dependency to vue3.3+ they'd be able to use hasInjectionContext (docs) as newer vue router versions use app.runWithContext (docs).

Bumping the dependency should also allow for some cleanup as vue3.3 also includes MaybeRef & MaybeRefOrGetter which I think urql-vue implements manually at the moment.

I also had a look at @tanstack/vue-query and they use getCurrentScope() so that could also be an option but the vue docs dont mention which version its available from.

smc13 avatar Mar 20 '25 03:03 smc13

Have the same problem. I wanted to have a store with a user and their role that will use useQuery to use it inside the beforeEach guard of the router to manage routing based on roles. As a workaround for now, I just used graphql client with a direct query inside the store

Sengulair avatar May 26 '25 14:05 Sengulair