loading...

How to access '$apollo' outside vue component?

mittalyashu profile image Yashu Mittal ・1 min read

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

Posted on Feb 26 '19 by:

mittalyashu profile

Yashu Mittal

@mittalyashu

I <3 to be a developer and designer.

Discussion

markdown guide
 

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