Search code examples
vue.jsgraphqlnuxt.jsapollopinia

Get result of useQuery with Apollo and Nuxt.js


I'm trying to use the useQuery function (from package '@vue/apollo-composable').

This function doesn't return a promise, just refs to result, loading etc. so I can't directly use this data in my store (Pinia).

Currently I have this code:

fetchArticle: function (id: string) {
      // check if article is already in cache
      const cache = this.articles.find(a => a.id == id);
      if (cache && !cache.partial) return cache;
      // fetch article from server
      const { result: article } = useQuery<{ article: Article }>(GET_ARTICLE, { id });
      // update state, but... when `article` contains data? 
    },

When I'am in a store I don't know how to wait for request end.

I tried to transform useQuery to return promise but that doesn't work, Nuxt.js freeze on server with this code:

fetchArticle: async function (id: string) {
      // check if article is already in cache
      const cache = this.articles.find(a => a.id == id);
      if (cache && !cache.partial) return cache;
      // fetch article from server
      const { onResult, result } = useQuery<{ article: Article }>(GET_ARTICLE, { id });
      const article = result.value?.article || (await new Promise(r => onResult(({ data }) => r(data.article))));
      if (!article) return;
      const data = { ...article, partial: false };
      this.articles = this.articles.map(a => (a.id == id ? data : a)) as Article[];
      // return article
      return article;
    },

Informations

  • Store: Pinia
  • Versions: Nuxt 3.1.2; @vue/apollo-composable 4.0.0-beta.2

Solution

  • I use the apollo client like this:

    // The creation of the client
    // This part is on a base class, that all of my Service extends
    this.apolloClient = new ApolloClient({
      link: //the link,
      cache: new InMemoryCache(),
      name: "My APP name",
      version: `v${version.toString()}`,
      defaultOptions: defaultOptions //some options I customize
    });
    provideApolloClient(this.apolloClient);
    
    //The query
    // This part is on the Service class
    return this.apolloClient.query({ query: query, variables: { id: id }}).then((result) => {
      return result.data.myData;
    });
    

    I always used like this, never used the useQuery. In the link I use a combination of three, one for the Auth, one for Errors and one for the base URL