Last active
October 21, 2019 15:54
-
-
Save elmehdiabdi-src/137f128319c32d5dd53667b4ecd0918d to your computer and use it in GitHub Desktop.
apollo useQuery hooks :: vuejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { provide, inject, value, ref } from '@vue/composition-api'; | |
const ApolloSymbol = Symbol() | |
export function provideContextToAppolo(context) { | |
provide(ApolloSymbol, context) | |
} | |
export function useApollo() { | |
const apollo = inject(ApolloSymbol) | |
return apollo.root.$apollo | |
} | |
export function useQuery(options) { | |
const apollo = inject(ApolloSymbol) | |
const response = ref({ | |
loading: true | |
}) | |
const error = ref(null) | |
const q = apollo.root.$apollo.watchQuery(options) | |
q.subscribe({ | |
next(data) { | |
response.value = data | |
}, | |
error(error) { | |
error.value = error | |
} | |
}); | |
return { | |
response, | |
error, | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<dir class="content"></dir> | |
</template> | |
<script> | |
import gql from 'graphql-tag' | |
import { watch } from '@vue/composition-api'; | |
import { provideContextToAppolo, useApollo, useQuery } from './hooks/apollo.js' | |
export default { | |
setup(props, context) { | |
provideContextToAppolo(context) | |
// this call $appolo from your commpenent ;) | |
const apollo = useApollo() | |
console.log(apollo.loading) | |
// here how to implements appolo useQuery | |
const users = useQuery({ | |
query: gql`query { users(module: "memeber") }` | |
}) | |
watch(() => console.log(users.response.value)) | |
// this will print null | |
// after request succeed will prunt response object | |
watch(() => console.log(users.response.value.loading)) | |
// this will print true | |
// after request succeed will print false | |
return { | |
// | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment