Issue with vue-apollo package causing GraphQL query not to display on the frontend

Currently, I am expanding my knowledge of GraphQL and working on a project where I aim to display queries in the front end. To achieve this, I have incorporated the package GitHub - Akryum/vue-apollo: 🚀 Apollo/GraphQL integration for VueJS. However, I have encountered some difficulties as nothing is showing up yet. Interestingly, I have successfully implemented similar functionality using React, and now I am striving to replicate the same with Vue.

I have managed to execute queries in the backend using graphiql. Additionally, I have configured the express server to utilize CORS to facilitate data transmission. My project architecture consists of an express backend and a Vue frontend.

Express: server.js

const https = require('https');
const express = require('express');
const cors = require('cors');
const app = express();
const request = require("request");
const bodyParser = require('body-parser');
const { graphqlExpress, graphiqlExpress } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');

app.use(cors())

// Some fake data
const books = [
  {
    title: "Harry Potter and the Sorcerer's stone",
    author: 'J.K. Rowling',
  },
  {
    title: 'Jurassic Park',
    author: 'Michael Crichton',
  },
];

// The GraphQL schema in string form
const typeDefs = `
type Query {
  hello: String
}
`;

// The resolvers
const resolvers = {
  Query: {
    hello(root, args, context) {
      return "Hello world!"
    },
  }
};

// Put together a schema
const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

// The GraphQL endpoint
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));

// GraphiQL, a visual editor for queries
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));

// Start the server
app.listen(3000, () => {
  console.log('Go to http://localhost:3000/graphiql to run queries!');
});

Vue: main.js

import Vue from 'vue'
import App from './App.vue'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'

const httpLink = new HttpLink({
  // You should use an absolute URL here
  uri: 'http://localhost:3000/graphql',
})

// Create the apollo client
const apolloClient = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
  connectToDevTools: true,
})

// Install the vue plugin
Vue.use(VueApollo)

const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
})

new Vue({
  el: '#app',
  provide: apolloProvider.provide(),
  render: h => h(App),
})

Vue.config.productionTip = false



new Vue({
  render: h => h(App)
}).$mount('#app')

Vue: App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <BookList />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import BookList from './components/BookList.vue';

export default {
  name: 'app',
  components: {
    HelloWorld,
    BookList
  }
};
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Vue: BookList.vue

<template>
<div>
    <h1>
        Book List
    </h1>
    <p>
      {{hello}}
    </p>
    </div>
</template>

<script>
import gql from 'graphql-tag';

export default {
  data() {
    return {
      // Initialize your apollo data
      hello: ''
    };
  },
  apollo: {
    // Simple query that will update the 'hello' vue property
    hello: gql`
      {
        hello
      }
    `
  }
};
</script>

Answer â„–1

After some investigation, I discovered the issue. The problem stemmed from inadvertently mounting Vue twice within the main.js file. It seems that the second instance of Vue was likely overriding the first one, causing it to lack the necessary provider attachment.

Removing the following code snippet from Vue: main.js effectively resolves the issue.

new Vue({
  render: h => h(App)
}).$mount('#app')

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

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

Having trouble reaching the upload file in PHP

I am attempting to transfer files to a remote server using JavaScript, with PHP as the backend. The JavaScript code seems to be functioning properly, but on the PHP side, the $_FILES and $_POST arrays are empty. However, the $_SERVER array contains some da ...

Drag and drop a Jquery image onto the div with its top left corner

Drop targets: <div id="targetContainer" style="width:100px; height:100px;> <div id="tar_0-0" class="target" style="position: relative; float:left; width:50px; height:50px; background-color: #fff;"></div> <div id="tar_1-0" class="t ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...

React Router's nested route causes a full page reload when navigating

I have been working on setting up nested routing in React Router and here is my code: import React from 'react'; import DefaultSwitch from './components/DefaultSwitch/DefaultSwitch'; import './scss/App.scss'; const App = () ...

What methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...

How to Implement Multi Select Drag and Drop Feature in Angular 4?

Currently, I am implementing Angular 2 Drag-and-Drop from this library to enable the selection of list items using a drag and drop method. However, I have encountered issues with its functionality on touch devices and when attempting to perform multiple it ...

The JavaScript code is not running as expected!

i have this index.html file: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Using React and Material-UI to dynamically populate a table with data retrieved from

Material ui table utilizes data in a specific format. rows: [ createData(1, "dashboard", "details"), createData(2, "product", "product details"), ].sort((a, b) => (a.id < b.id ? -1 : 1)) When the API responds with data stored in st ...

Having issues retrieving and utilizing response status code following the initial then() method in a Promise

My goal is to utilize the response status code, which is initially available in the first then function along with the JSON response data. However, I am encountering a SyntaxError: Unexpected token U in JSON at position 0. Here is the snippet of the promi ...

What is the purpose behind enclosing a function expression in parentheses in JavaScript (apart from creating an IIFE)?

While delving into some advanced JavaScript concepts, I stumbled upon a piece of jQuery code on GitHub that caught my eye. It was an anonymous function wrapped in parentheses, which you can find here. Although I'm familiar with Immediately Invoked Fu ...

A step-by-step guide on modifying the box-shadow color using jquery

I have developed some JavaScript code that adjusts the box-shadow of buttons to be a darker version of their background color. This allows users to dynamically change the button background colors. The current code successfully changes the box shadow based ...

Ways to terminate all AJAX requests within a for loop

Is there a way to cancel all AJAX requests that are being handled by a for loop? var url = ["www.example.com","www.example2.com",....]; for (var i = 0; i < url.length; i++) { var XHR = $.get(url[i], function(data) { //do something }); } I attemp ...

What could be causing the second image to not drop in the proper position in an HTML and JavaScript environment?

I am encountering an issue with a simple drag and drop implementation using images in my code. The first image works fine, but for some reason the second image does not display correctly when dragged inside the div boxes; it appears outside of the box. Can ...

Exploring navigation options in VueJS with the router

I recently completed a tutorial on integrating Okta OAuth with VueJS. In my application, I have set up a default page that displays the "App.vue" component and switches to the "About.vue" component upon clicking the "/about" route. However, I encountered a ...

Ways to extract values from a javascript hash map by exclusively incorporating an array

So here's the issue I'm encountering. Let's consider the following scenario: let surfaces: Map<any, any> = new Map([{"83.1" => Object}, {"84.1" => Object}]) let arr1 = ["83.1"] This is the desired o ...

Fetching values from dynamically generated elements in a Vue.js loop

I am currently working on creating a table that includes checkboxes and text fields based on an array of items, essentially building a "questionnaire" where the questions are pulled from a database. My question now is how can I efficiently retrieve inform ...

Changing from localhost:3000/admin to localhost:3000 within the local server

I am currently developing a node.js application. My goal is to have the homepage rendered after the admin successfully uploads data, transitioning from localhost:3000/admin to localhost:3000. I attempted to achieve this using the code snippet below: route ...

Is the create attachment function of the Microsoft Graph API not functioning properly?

I've been trying to create an attachment for my messages by following the documentation provided, but unfortunately, the API seems to be giving me some trouble. I referred to the document at for guidance. Below is the JavaScript code that I have bee ...