2.0.2 • Published 4 years ago

@ipr/vuex-graphql-api v2.0.2

Weekly downloads
6
License
MIT
Repository
-
Last release
4 years ago

@ipr/vuex-graphql-api

Vuex plugin for GraphQL API

Installation

yarn add @ipr/vuex-graphql-api

Usage

The plugin leverages provide and inject from the Composition API internally and exposes provideStore and useStore composition functions.

  1. Init the Apollo client and Vuex store using the provideStore function:
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
import { provideStore } from '@ipr/vuex-graphql-api'
import App from './App.vue'

Vue.use(VueCompositionApi)

new Vue({
  setup() {
    provideStore('http://localhost:4000/graphql', null)
  },
  store,
  render: h => h(App)
}).$mount('#app')
  1. Connect the API to the components with useStore function, then:
  • trigger actions using the Vuex dispatch method with the Apollo query payload
  • access store state through the Vuex getters property
import Vue from 'vue'
import { Store } from 'vuex'
import { useStore } from '@ipr/vuex-graphql-api'
import { getEntities, getEntityById } from '@/graphql/queries.gql'

export default {
  name: 'app',
  props: {
    api: Object as () => Store<any>
  },
  setup() {
    return {
      api: useStore()
    }
  },
  computed: {
    items() {
      return Object.values(
        this.api.getters.data?.todo?.todo || []
      )
    },
    selected() {
      return Object.create(
        this.api.getters.active?.todo?.todoById || {}
      )
    }
  },
  mounted() {
    this.fetchData('todo')
  },
  methods: {
    async fetchData(typename) {
      await this.api.dispatch('findMany', {
        typename,
        query: getEntities
      })

      const { id } = this.items[0]

      await this.api.dispatch('findOne', {
        typename,
        query: getEntityById,
        variables: { id }
      })
    }
  }
}