Skip to content

Commit

Permalink
fix(hooks): additional error message when used outside of setup function
Browse files Browse the repository at this point in the history
  • Loading branch information
DamianOsipiuk committed Jul 1, 2021
1 parent b208119 commit 8a77a7e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/__mocks__/vue-demi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ module.exports = {
inject: jest.fn(),
provide: jest.fn(),
onUnmounted: jest.fn(),
getCurrentInstance: jest.fn(),
getCurrentInstance: jest.fn(() => ({ proxy: {} })),
};
10 changes: 9 additions & 1 deletion src/useQueryClient.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { inject } from "vue-demi";
import { getCurrentInstance, inject } from "vue-demi";

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

export const VUE_QUERY_CLIENT = "VUE_QUERY_CLIENT";

export function useQueryClient(): QueryClient {
const vm = getCurrentInstance()?.proxy;

if (!vm) {
throw new Error(
"vue-query hooks can only be used inside setup() function."
);
}

const queryClient = inject<QueryClient>(VUE_QUERY_CLIENT);

if (!queryClient) {
Expand Down
10 changes: 9 additions & 1 deletion tests/useQueryClient.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { inject } from "vue-demi";
import { getCurrentInstance, inject } from "vue-demi";
import { useQueryClient, VUE_QUERY_CLIENT } from "../src/useQueryClient";

describe("useQueryClient", () => {
const injectSpy = inject as jest.Mock;
const getCurrentInstanceSpy = getCurrentInstance as jest.Mock;

beforeEach(() => {
jest.restoreAllMocks();
Expand All @@ -27,4 +28,11 @@ describe("useQueryClient", () => {
expect(injectSpy).toHaveBeenCalledTimes(1);
expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT);
});

test("should throw an error when used outside of setup function", () => {
getCurrentInstanceSpy.mockReturnValueOnce(undefined);

expect(useQueryClient).toThrowError();
expect(getCurrentInstanceSpy).toHaveBeenCalledTimes(1);
});
});

1 comment on commit 8a77a7e

@vercel
Copy link

@vercel vercel bot commented on 8a77a7e Jul 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.