Justin
Justin

Reputation: 653

How to get data into my Nuxt app for all pages/components

I have a file called config-ingest.js in my plugins directory with the following:

import gql from 'graphql-tag'

export default ({ app }, inject) => {

  const client = app.apolloProvider.defaultClient;

  const apps = gql`
    query {
      apps: allApps {
        key
        tree
      }
    }
  `;

  client.query({ query: apps }).then(response => {
    inject('configStructure', response.data.apps);
  });

}

Although the data is successfully retrieved, it doesn't seem to be available in all my pages and components.

If I want to get data from another server that should be available to all my pages, how would I do this? I want to stick this data in it's own file so I can get the data from any component or page when I please.

Upvotes: 0

Views: 854

Answers (2)

Justin
Justin

Reputation: 653

I was able to do the following in store/index.js:

import gql from 'graphql-tag'

export const state = () => ({
  apps: []
})

export const mutations = {
  SET_APPS (state, apps) {
    state.apps = apps
  },
}

export const getters = {
  getApps (state) {
    return state.apps;
  },
  }
}

export const actions = {
  async nuxtServerInit ({ commit }, { app }) {

    const client = app.apolloProvider.defaultClient;

    const apps = gql`
        query {
          apps: allApps {
            key
            label
            tree
          }
        }
      `;

    await client.query({ query: apps }).then(response => {
      commit('SET_APPS', response.data.apps)
    });
  }
}

Upvotes: 0

Pjotr Raskolnikov
Pjotr Raskolnikov

Reputation: 1688

You should use the Vuex Store for that. https://nuxtjs.org/guide/vuex-store/

Upvotes: 1

Related Questions