@ipr/vuex-graphql-api
v2.0.2
Published
Vuex plugin for GraphQL API
Downloads
4
Readme
@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.
- 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')
- Connect the API to the components with
useStore
function, then:
- trigger actions using the Vuex
dispatch
method with the Apolloquery
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 }
})
}
}
}