Skip to content

Commit 8a77a7e

Browse files
committed
fix(hooks): additional error message when used outside of setup function
1 parent b208119 commit 8a77a7e

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

src/__mocks__/vue-demi.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,5 @@ module.exports = {
1010
inject: jest.fn(),
1111
provide: jest.fn(),
1212
onUnmounted: jest.fn(),
13-
getCurrentInstance: jest.fn(),
13+
getCurrentInstance: jest.fn(() => ({ proxy: {} })),
1414
};

src/useQueryClient.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1-
import { inject } from "vue-demi";
1+
import { getCurrentInstance, inject } from "vue-demi";
22

33
import type { QueryClient } from "react-query/types";
44

55
export const VUE_QUERY_CLIENT = "VUE_QUERY_CLIENT";
66

77
export function useQueryClient(): QueryClient {
8+
const vm = getCurrentInstance()?.proxy;
9+
10+
if (!vm) {
11+
throw new Error(
12+
"vue-query hooks can only be used inside setup() function."
13+
);
14+
}
15+
816
const queryClient = inject<QueryClient>(VUE_QUERY_CLIENT);
917

1018
if (!queryClient) {

tests/useQueryClient.test.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import { inject } from "vue-demi";
1+
import { getCurrentInstance, inject } from "vue-demi";
22
import { useQueryClient, VUE_QUERY_CLIENT } from "../src/useQueryClient";
33

44
describe("useQueryClient", () => {
55
const injectSpy = inject as jest.Mock;
6+
const getCurrentInstanceSpy = getCurrentInstance as jest.Mock;
67

78
beforeEach(() => {
89
jest.restoreAllMocks();
@@ -27,4 +28,11 @@ describe("useQueryClient", () => {
2728
expect(injectSpy).toHaveBeenCalledTimes(1);
2829
expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT);
2930
});
31+
32+
test("should throw an error when used outside of setup function", () => {
33+
getCurrentInstanceSpy.mockReturnValueOnce(undefined);
34+
35+
expect(useQueryClient).toThrowError();
36+
expect(getCurrentInstanceSpy).toHaveBeenCalledTimes(1);
37+
});
3038
});

0 commit comments

Comments
 (0)