diff --git a/packages/graphql-hooks/src/useClientRequest.js b/packages/graphql-hooks/src/useClientRequest.js index 5979b858..0be0637c 100644 --- a/packages/graphql-hooks/src/useClientRequest.js +++ b/packages/graphql-hooks/src/useClientRequest.js @@ -133,7 +133,6 @@ function useClientRequest(query, initialOpts = {}) { // arguments to fetchData override the useClientRequest arguments const fetchData = useDeepCompareCallback( newOpts => { - if (!isMounted.current) return Promise.resolve() const revisedOpts = { ...initialOpts, ...newOpts @@ -145,6 +144,18 @@ function useClientRequest(query, initialOpts = {}) { operationName: revisedOpts.operationName } + if (!isMounted.current) { + return Promise.resolve({ + error: { + fetchError: new Error( + 'fetchData should not be called after hook unmounted' + ) + }, + loading: false, + cacheHit: false + }) + } + const revisedCacheKey = client.getCacheKey(revisedOperation, revisedOpts) // NOTE: There is a possibility of a race condition whereby diff --git a/packages/graphql-hooks/test/unit/useClientRequest.test.js b/packages/graphql-hooks/test/unit/useClientRequest.test.js index b0a52f49..0749ddf0 100644 --- a/packages/graphql-hooks/test/unit/useClientRequest.test.js +++ b/packages/graphql-hooks/test/unit/useClientRequest.test.js @@ -473,7 +473,7 @@ describe('useClientRequest', () => { expect(state).toEqual({ cacheHit: false, loading: true }) }) - it('returns undefined instantly if not mounted', async () => { + it('returns result with error instantly if not mounted', async () => { let fetchData, state const { unmount } = renderHook( () => @@ -487,8 +487,16 @@ describe('useClientRequest', () => { ) unmount() - const result = await act(fetchData) - expect(result).toBe(undefined) + + let result + await act(async () => { + result = await fetchData() + }) + + expect(result.data).toBe(undefined) + expect(result.loading).toBe(false) + expect(result.cacheHit).toBe(false) + expect(result.error.fetchError).toBeInstanceOf(Error) expect(mockClient.request).not.toHaveBeenCalled() expect(state).toEqual({ cacheHit: false, loading: true }) })