Search code examples
axiosgraphqlnuxt.jsapollo

How to use GraphQL queries while using nuxt-apollo?


I am trying to query the data from a Django endpoint which lists all my articles using Graphene Django. I followed all documentations but cannot understand how to fetch data in vuex action.

When using GraphiQl I can get the data answer. I have arranged my nuxt.config.js

apollo: {
    tokenName: "nuxt-apollo", // specify token name
    cookieAttributes: {
      expires: 7 // optional, default: 7 (days)
    },
    defaultOptions: {
      $query: {
        fetchPolicy: "network-only",
        errorPolicy: "all"
      }
    },
    watchLoading: "@/apollo/loadingHandler.js",
    errorHandler: "@/apollo/errorHandler.js",
    clientConfigs: {
      default: {
        httpEndpoint: 'http://localhost:8000/api/articles/graphql/'
      }
    }
  },

Now In my vuex store, but I cannot figure how to query and use data, I tried to query as below but no success:

async fetchArticles({ commit }) {
    try {
      const response =  this.$axios.$get(
        'articles/graphql/',
        {
          query: query({
            query: gql`
              query Articles {
                allArticles {
                  id
                  title
                }
              }
            ` 
          }) 
        }
      )
        
    } catch (error) {
      commit('setError', error)
    }
  },

Can you help me to fix my query? Thanks


Solution

  • You can simply install graphql-tag library for creating queries to send over Apollo Client.

    Also you can create file named article.graphql :

    query Articles {
        allArticles {
          id
          title
        }
     }
    

    Also pass parameters to query like this:

    query ($param: [String]) {
       //your query
    }
    

    And usage in store:

    import articleQuery from './queries/article.graphql';
    ....
    // some store action
    async fetchArticles({ commit }) {
        const client = this.app.apolloProvider.clients.default;
    
        // Optional Param   
        // const param = format(new Date(), 'yyyy-MM-dd');
    
        const queryResult = 
           await client.query({
              query: articleQuery,
              // Optional (if query contain parameter you can use)
              // variables: { param }
            });
    }