Is it feasible to merge Apollo queries within the context of Nuxt?

Incorporating nuxt and apollo together using the https://github.com/nuxt-community/apollo-module module has been a successful venture.

A GraphQL query was crafted and tested in GraphiQL to obtain information about a specific page along with general SEO details:

{
  entries(section: [pages], slug: "my-page-slug") {
    slug
    title
  }
  seomatic(uri: "/") {
    metaTitleContainer
    metaTagContainer
    metaLinkContainer
    metaScriptContainer
    metaJsonLdContainer
  }
}

The goal was to retrieve this data using apollo in nuxt:

Initial attempts were made as per the following:

<script>
import page from '~/apollo/queries/page'
import seomatic from '~/apollo/queries/seomatic'

export default {
  apollo: {
    entries: {
      query: page,
      prefetch: ({ route }) => ({ slug: route.params.slug }),
      variables() {
        return { slug: this.$route.params.slug }
      }
    },
    seomatic: {
      query: seomatic,
      prefetch: true
    }
  },
…

However, the execution raised an error:

GraphQL error: Cannot query field "seomatic" on type "Query".

Subsequently, an issue was discovered at: https://github.com/apollographql/apollo-tooling/issues/648 which questioned if this could be attributed to the apollo nuxt module. Implementing the suggested fix did not rectify the situation.

An attempt was made to consolidate the two calls into a single query:

fragment SeoMaticFragment on Root {
  seomatic(uri: "/") {
    metaTitleContainer
    metaTagContainer
    metaLinkContainer
    metaScriptContainer
    metaJsonLdContainer
  }
}

query myQuery($slug: String!) {
  entries(section: [pages], slug: $slug) {
    slug
    title
  }

  SeoMaticFragment
}

~/apollo/queries/page.gql

This approach initially encountered an error:

fragment Unknown type "Root"

  1. What is the optimal method to combine these queries?
  2. Why are the requests failing?
  3. Is there a way to enable batching as detailed here:

-

const client = new ApolloClient({
 // ... other options ...
 shouldBatch: true,
});

Your insights and assistance on this matter are greatly appreciated.

Answer №1

After exploring different avenues, a breakthrough was made in solving this issue. The key was leveraging the result hook within vue-apollo to effectively tackle the problem:

Take a look at this functional code snippet:

<script>
import gql from 'graphql-tag'

const query = gql`
{
    entries(section: [pages], slug: "my-example-page-slug") {
        slug
        title
    }
    seomatic(uri: "/") {
        metaTitleContainer
        metaTagContainer
        metaLinkContainer
        metaJsonLdContainer
    }
}
`

export default {
    data: () => {
        return {
            page: false,
            seomatic: {}
        }
    },
    apollo: {
        entries: {
            query,
            prefetch: ({ route }) => ({ slug: route.params.slug }),
            variables() {
                return { slug: this.$route.params.slug }
            }
        },
        result(result) {
            this.entries = result.data.entries
            this.seomatic = result.data.seomatic
        }
    }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Zustand through Laravel validation errorsUnderstanding Zustand can be

I'm currently working on incorporating Zustand into my NextJS application. I have set up a Laravel endpoint for user login functionality. When there are validation errors, the endpoint sends back JSON in the following format: { "message" ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

Parsing JSON into a List of Objects

Here is a filter string in the following format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I am looking to deserialize this into a Generic list of items. Any tips on how I can accomplish this? ...

What is the best way to continuously compare two date variables every minute using Javascript?

In my script, I have two date variables - one representing the current time and the other two minutes later. My goal is to compare both values every minute and trigger a function when the current time is greater than or equal to the latter time. Unfortun ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

Incorporating S3 images into vanilla JavaScript within a Django storages environment

I am facing a simple issue that I cannot seem to resolve. I have configured Django storages to serve static files from S3. In my template, I define the image source like this: "{% static 'fun_share/img/logo/logo.svg' %}" with STATIC_UR ...

Setting a default value in ng-options can be accomplished by using the ng-init

One way to set a dropdown list with a default value in AngularJS is by using the following code: <select name="repeatSelect" id="repeatSelect" ng-model="repeatSelect" ng-init="repeatSelect = data[0].id"> <option ng-repeat="option in data" val ...

What is the process of retrieving a property value from a database using selected values from cascaded drop-down lists?

I am facing a challenge where I need to extract a property of an entity by passing the IDs of selected items from a cascaded dropdown list. The requirement is to update the price every time there is a change in either level 1 or level 2 of the cascading dr ...

What is the best way to convert an ajax get request into a post request using jQuery?

I'm interested in transforming a GET request to a POST request: $.ajax({ url: '/items?ids=' + value.join(','), method: 'get', dataType: 'json' }) What changes do I need to make to turn this into a ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Connecting two sets of data from a mongoDB database using vue.js

Hey there, I'm a newcomer to vue and mongodb. I've set up two collections - one for storing user details and the other for business details. When a business registers through a form, their information is saved in mongodb. Now, I've created a ...

Having problems with Javascript and CSS not playing well together?

I have implemented a button from this source, but it does not appear correctly on my page. You can view the screenshot here. It seems like there is a conflict between the saved changes and the CSS. How can I resolve this issue? In addition, I am facing ...

JQuery displays 'undefined' on checkbox loaded via Ajax

Currently, I am utilizing a checkbox to activate my select Option tag. The select option tag and checkbox are both loaded via ajax. While the select option works perfectly, the checkbox displays as undefined. However, it functions properly in enabling my d ...

What's the point of using defer() in Node.js Q promises when you have the option to simply use this

I had a plan in mind: somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Let's celebrate }) .done(); Unfortun ...

Access the plugin object from a Vue.js 2 component using typescript

I devised a plugin object to handle the regular expressions used in my application in a more global manner. Here's an example of how it looks: import Vue from "vue"; Vue.prototype.$regex = { //isEmail function implementation goes here } ...

Using CSS selectors in Framework7 Vue allows for precise targeting and styling

I am currently working on developing a Cordova/Phonegap application using vue.js and the Framework7. I have been able to utilize functions like "onClick" by using the "v-on:click="OnClick" attribute within an HTML element. It's worth noting that Frame ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Retrieve user information from Auth0 once the user has completed the signup process

I am looking to integrate the ability to create new users on Auth0 through my admin panel. Currently, I am utilizing Auth0 lock for signups, but now I need to store these users in my Database, which requires their email and Auth0 user ID. I am exploring o ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...