fix: use hasInjectionContext in useApolloClient before calling inject (#1529)

Co-authored-by: Dawid Kopys <dawid.kopys@creativestyle.pl>
This commit is contained in:
Dawid Kopys
2024-01-24 09:41:26 +01:00
committed by GitHub
parent c795f25708
commit 460a0dbd11
4 changed files with 56 additions and 2 deletions
@@ -0,0 +1,42 @@
<script lang="ts">
import { apolloClient } from '@/apollo'
import gql from 'graphql-tag'
import { provideApolloClient, useQuery } from '@vue/apollo-composable'
import { ref, defineComponent, hasInjectionContext, effectScope, computed, watch, onBeforeUnmount } from 'vue'
const hello = ref('')
const scope = effectScope()
scope.run(() => {
const query = provideApolloClient(apolloClient)(() => useQuery(gql`
query hello {
hello
}
`))
const innerHello = computed(() => query.result.value?.hello ?? '')
watch(innerHello, (newHello) => {
hello.value = newHello
}, {
immediate: true,
})
})
export default defineComponent({
setup () {
onBeforeUnmount(() => {
scope.stop()
})
return {
hello,
}
},
})
</script>
<template>
<div class="no-setup-scope-query">
{{ hello }}
</div>
</template>
@@ -72,5 +72,12 @@ export const router = createRouter({
layout: 'blank',
},
},
{
path: '/no-setup-scope-query',
component: () => import('./components/NoSetupScopeQuery.vue'),
meta: {
layout: 'blank',
},
},
],
})
@@ -119,4 +119,9 @@ describe('Vue 3 + Apollo Composable', () => {
cy.get('[data-test-id="global-loading"]').should('not.contain', 'Global loading...')
cy.contains('#app', 'Currently viewing # General')
})
it('supports queries outside of setup but within scope', () => {
cy.visit('/no-setup-scope-query')
cy.contains('.no-setup-scope-query', 'Hello world!')
})
})
@@ -1,4 +1,4 @@
import { getCurrentInstance, getCurrentScope, inject } from 'vue-demi'
import { hasInjectionContext, inject } from 'vue-demi'
import { ApolloClient } from '@apollo/client/core/index.js'
export const DefaultApolloClient = Symbol('default-apollo-client')
@@ -35,7 +35,7 @@ export function useApolloClient<TCacheShape = any> (clientId?: ClientId): UseApo
// Save current client in current closure scope
const savedCurrentClients = currentApolloClients
if (!getCurrentInstance() && !getCurrentScope()) {
if (!hasInjectionContext()) {
resolveImpl = (id?: ClientId) => {
if (id) {
return resolveClientWithId(savedCurrentClients, id)