0

I have a Vue 3 project and I'm working with Composition API. I'm communicating with my backend using Urql which is a graphql library which allows me to wrap API requests as composables. I'm new to Pinia, but after a bit of time working with Vue 2 + Vuex I can tell that one of the most common scenarios of writing actions was making API requests and updating the state (asynchronously) with the response. I'm trying to adopt the same technique in my current tech stack and facing some issues.

My problem is that I can't just use the old fashioned fetch/axios/got libraries to execute requests whenever I want, I should first register the composable somewhere. I've seen that one option is to call the composable's use* function in the store's state section, but it seems weird to me to have such thing in there as it has nothing to do with the state. I've tried executing the use* method directly in an action, but it seems to fail. I wonder if I'm missing some best-practice way to work with Urql and Pinia, as things are getting more and more complex even though my usecase is pretty common and simple. Should I use Urql's Client directly? Any other good solution to make gql requests from within my store actions?

export const useUsersStore = defineStore('app', {
  actions: {
    setUser() {
      const response = (await useUsers()).data // this wont work
    },
  }
);
Shay Yzhakov
  • 975
  • 2
  • 13
  • 31
  • "but it seems weird to me to have such thing in there as it has nothing to do with the state." - you need to have access to `useUsers()` result inside a store, so it's a part of the state. It would be the same if you'd need to access it inside a component, it would be a part of its internal state. – Estus Flask Nov 07 '22 at 22:42
  • Thats why using Urql inside the store feels weird. Inside a component, it makes sense to use Urql functions like `useUsers()` that handles the reactivity of the results. But store concept has nothing to do with composition API in my opinion, so using `useUsers` in there doesn't feel right. But I'm not sure about the best practices of Pinia.. Should I make API request from within actions? (guess I do..) If so, how can I execute them using Urql? – Shay Yzhakov Nov 08 '22 at 10:38
  • Quite the opposite, Pinia is relatively thin wrapper around Vue composition. You'd have to use composition api directly when using Pinia setup function. It's the same for any kind of store. If you want something to belong to store instance, you have to assign it on store creation. In case of pinia options, this is done in state function. Then it can be accessed in actions via this context. Can't say specifically for urql. – Estus Flask Nov 08 '22 at 11:00

0 Answers0