Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Default Apollo Queries" VS "AsyncData" (Nuxt.js)

Tags:

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.

like image 235
Drew Baker Avatar asked Apr 27 '19 22:04

Drew Baker


1 Answers

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.

like image 160
Andrew1325 Avatar answered Sep 23 '22 22:09

Andrew1325