What is the best way to incorporate Vue Apollo into a Vue Vite project?

I'm currently working on integrating Vue Apollo into a Vite project using the composition API. Here is how my main.js file looks:

import { createApp } from 'vue'
import App from './App.vue'
import * as apolloProvider from '../apollo.provider'
import router from './router'

const app = createApp(App)

app
.use(router)
.use(apolloProvider.provider)
.mount('#app')

In the vue4 setup section, it is recommended to update the main.js like this:

import { createApp, provide, h } from 'vue'
import { DefaultApolloClient } from '@vue/apollo-composable'

const app = createApp({
  setup () {
    provide(DefaultApolloClient, apolloClient)
  },

  render: () => h(App),
})

I am encountering difficulties in integrating this code into my main.js. Every time I import DefaultApolloClient, my application gets stuck in a loop of refreshing itself. Any suggestions on how to resolve this issue?

p.s. Here is the content of my packages.json:

{
  "name": "kiddo-vite-frontend",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@vue/apollo-composable": "^4.0.0-alpha.17",
    "apollo-boost": "^0.4.9",
    "apollo-cache-inmemory": "^1.6.6",
    "apollo-client": "^2.6.10",
    "apollo-link": "^1.2.14",
    "apollo-link-context": "^1.0.20",
    "apollo-link-http": "^1.5.17",
    "graphql": "^16.5.0",
    "graphql-tag": "^2.12.6",
    "vue": "^3.2.30",
    "vue-apollo": "^3.1.0",
    "vue-router": "^4.0.15"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.3.3",
    "vite": "^2.9.9"
  }
}

Thank you.

Valerio

Answer №1

If you encounter a loop while starting the development server, it may be due to missing prerequisite dependencies. To fix this issue, follow the steps outlined below.

Starting with @vue/apollo-composable and Vue 3

  1. First, install the necessary prerequisites along with @vue/apollo-composable:

    $ npm install --save graphql graphql-tag @apollo/client
    $ npm install --save @vue/apollo-composable
    
  2. In your main.js file, add the following code to set up your Apollo client for use with GraphQLZero (a simulated online GraphQL API):

     import { createApp } from 'vue'
     import { DefaultApolloClient } from '@vue/apollo-composable'
     import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
     import App from './App.vue'
    
     const httpLink = createHttpLink({
       uri: 'https://graphqlzero.almansi.me/api',
     })
     const cache = new InMemoryCache()
     const apolloClient = new ApolloClient({
       link: httpLink,
       cache,
     })
    
     createApp(App)
       .provide(DefaultApolloClient, apolloClient)
       .mount('#app')
    
  3. Next, create a component that utilizes useQuery from @vue/apollo-composable:

     <script setup>
     import { useQuery } from '@vue/apollo-composable'
     import gql from 'graphql-tag'
    
     const { result } = useQuery(gql`
       query getUser {
         user(id: 1) {
           id
           name
         }
       }
     `)
     </script>
    
     <template>
       <h2>Hello {{ result?.user?.name ?? 'world' }}</h2>
     </template>
    
  4. Lastly, start the development server:

    $ npm run dev
    

Check out the demo here

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 the functionality of Kendo Grid within an Angular application

Currently, I am facing some challenges while trying to execute my Karma tests using the kendo grid within a fresh Angular project. The specifications for this specific component are outlined below: import { async, ComponentFixture, TestBed } from '@a ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Is there a way to programmatically select an option value in a v-select component using vue.js 2?

I'm attempting to designate the option with a value of 1 as selected, but I am encountering difficulties when using the v-select component from Vue.js. This is how I have attempted to achieve it - <v-select name="branchid" v-model="branchid" ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

Exploring Data in a Tree View Format on a PHP Website

Looking for advice on displaying categories and corresponding subcategories on the left side of my website (built using Php and Javascript). I would like the tree to be movable, similar to the functionality featured on this link: Any suggestions on how I ...

Display the input text value when the button is clicked

I am a beginner in JavaScript and have created this HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> Upon entering text into the input field and clicking on the submi ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

Finding the automatically generated ID of a new document in a subcollection in Firebase Firestore Web V9, using Javascript/React

When a user clicks, I generate a new document in a subcollection associated with that user's profile. Below is the function responsible for this: // Function to create a new checkout session document in the subcollection under the user's profile ...

Is there a way to execute a Vue method directly from a <div> element?

I'm currently using Blade to control parts of the HTML through conditional rendering. For instance, if the Laravel session login is present, I want to display a div that triggers a Vue method to open a login modal. At the moment, I am utilizing vue-js ...

Express and Firebase Function: Headers cannot be set once they have already been sent

My experience has been mainly with the Hapi framework for developing RESTful APIs. However, for my current project, I decided to use Express and I'm encountering some confusion regarding the issues that are arising. While testing the POST endpoint us ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

Using Jquery for Animation: Tips on Revealing Text After Changing Element Color or Styles

Hey everyone, I ran into a bit of trouble while working with jQuery and trying out some animations. My goal was to make a textbox appear and display text when a button is highlighted, similar to a gallery setup. However, I managed to get halfway through th ...

How to incorporate user-submitted form data into the existing state using React

I am currently working on a React project that involves a form input. The goal is for the user to input a number into the field, and then take that number and add it to another number in the application's state. For example, if this.state.data initia ...

Guide on transferring datetime information from a popup dialog to an MVC controller

My goal is to create a button that, when clicked, opens a dialog allowing the selection of start and end dates. Upon clicking ok/submit, the selected datetime should be passed to a controller [HttpPost] action method. Here's what I have attempted so f ...

Do I have to additionally check the data type using typeof when implementing PropTypes in my code?

I have a custom method called onNotifyChange that is triggered in the onChange event of an input element. This method has been defined with a PropType of func. MyComponent.propTypes = { onNotifyChange: PropTypes.func, } When invoking the onNotifyCha ...

What methods can I employ in Javascript to automatically display search results obtained from multiple HTTP search queries?

In my tampermonkey script, I am attempting to process an array of names by performing a search and printing the page for each one. The script runs automatically upon loading the page, hence the necessity of the if statement. $(document).ready(function(){ ...

Transferring an array from PHP to Javascript using GET method

Can someone help me figure out how to pass an array to Javascript after it sends a GET request to PHP? I've got the data sending and retrieving down pat, but now I'm stuck on how to send the data back as an array. Here's what I have so far: ...

problem encountered when loading an HTML file within another HTML file using AJAX

By clicking a button, I successfully loaded a full HTML page (refer to the structure below) into another HTML page. <!--START:HTML to be loaded by ajax--> <head> <!--START: The content inside this head tag is not processed while the pag ...

Press the button in an HTML document to activate JavaScript

What could be the issue with my code? I have a button in HTML <a class="btn btn-warning btn-mini publish-btn" href="#" data-rowid="@computer.id" data-toggle="modal" data-target="#myModal">Outdated</a> and my modal <fieldset style="text-al ...