22

I'm building a site with Nuxt/Vue, and it's using a GraphQL backend API. We access this using the Apollo module for Nuxt.

In a page component, you can do this (I think this is called a Smart Query, but I'm not sure):

apollo: {
  pages: {
    query: pagesQuery,
      update(data) {
        return _get(data, "pageBy", {});
      }
    },
  }
}

But you can also do the query like this I think, using the Nuxt asyncData hook:

asyncData(context) {
  let client = context.app.apolloProvider.defaultClient;
  client.query({query, variables})
        .then(({ data }) => {
          // do what you want with data
        });
  }
}

I'm not sure what the difference is between these two ways, and which is better. Does anyone know? I couldn't find an explanation in the docs anywhere.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Drew Baker
  • 14,154
  • 15
  • 58
  • 97

1 Answers1

17

Yeah, good question. The code you have shown at the top is indeed called a Smart Query. In fact

Each query declared in the apollo definition (that is, which doesn't start with a $ char) in a component results in the creation of a smart query object.

A nuxt project using the @nuxtjs/apollo module can use these out of the box. The beauty of the smart query is the options that it comes with and one of these is the 'prefetch' option. This, as it sounds, allows prefetching and is by default set to true. It can also accept a variables object or a function. You can see the docs here.

This means that the outcome of a smart query or an asyncData query will essentially be the same. They should be resolved in the same timeframe.

So why choose one or the other? This would probably be down to preference, but with all the options that a smart query allows you can do a lot more, and you can include subscriptions which might not be possible in asyncData.

More about smart queries here.

bob
  • 2,674
  • 1
  • 29
  • 46
Andrew1325
  • 3,519
  • 1
  • 14
  • 25
  • So a smart query isn't blocking in anyway? I worry that my SSR page is going to have to wait for all these queries to finish before showing anything to the user. – Drew Baker Apr 28 '19 at 05:42
  • 2
    My understanding is that the query behaves in the same manner as asyncData would, in that it is asynchronous, and the server prefetches data into a dedicated data store while pre-rendering and injects that into the client when complete. I've not noticed any blocking behaviour but only have a couple of projects utilising them to go by. – Andrew1325 Apr 28 '19 at 07:36
  • 9
    Asyncdata wait for data to be ready before rendering both on client and server – Aldarund Apr 28 '19 at 08:43