DEV Community

Yashu Mittal
Yashu Mittal

Posted on

How to access '$apollo' outside vue component?

Don't know about vue-apollo, checkout the documentation.

If you will try to use $apollo outside the vue component, you will get similar error.

Vue apollo error

To make this work, instead of initializing the apollo client in the App.vue file, initialize it in another file. Something like mixin/apollo.js, and export the client:

const httpLink = new HttpLink({
    uri: process.env.VUE_APP_DB_URL,
})

const cache = new InMemoryCache()

export const apolloClient = new ApolloClient({
    link: httpLink,
    cache
})

Then, import back the export into App.vue file:

import { apolloClient } from './clients.js';

Vue.use(VueApollo)

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

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

Then you can import the same client in any other file you want

import { apolloClient } from './client.js';
import gql from "graphql-tag"

export default function userExist(username) {
apolloClient
    .query({
        query: gql`
    query($username: String!) {
        login(username: $username) {
            username
            email
        }
    }
`,
        variables: {
            username: username
        }
    })
    .then(res => {
        console.log(res);
        return res
    })
    .catch(err => {
        console.log(err);
        return err
    });
}

Reference

Thanks

Top comments (2)

Collapse
 
soheilarmin profile image
Soheil Armin

Good job,
But apolloClient is a different type than $apollo
$apollo is referencing DollarApollo instance. I'm trying to find a to reference DollarApollo from outside of a Vue component. I will let you know if I could.

Collapse
 
ctwhome profile image
J. Gonzalez

hI!, would you know how to use this with Nuxt and vue-apollo?