Skip to content

Commit

Permalink
feat: add onCompleted callback support for useQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
willnguyen1312 committed Mar 26, 2024
1 parent 77671e5 commit 444538a
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/tricky-walls-exercise.md
@@ -0,0 +1,5 @@
---
'@shopify/react-graphql': minor
---

Add onCompleted callback support for useQuery
6 changes: 6 additions & 0 deletions packages/react-graphql/src/hooks/query.ts
Expand Up @@ -48,6 +48,7 @@ export default function useQuery<
notifyOnNetworkStatusChange,
context,
ssr = true,
onCompleted,
} = options;

const variables: Variables = options.variables || ({} as any);
Expand Down Expand Up @@ -176,6 +177,11 @@ export default function useQuery<
) {
return;
}

if (onCompleted && !status.loading && !status.error) {
onCompleted(status.data);
}

invalidateCurrentResult();
},
(error) => {
Expand Down
22 changes: 21 additions & 1 deletion packages/react-graphql/src/hooks/tests/query.test.tsx
Expand Up @@ -95,7 +95,7 @@ describe('useQuery', () => {
);
});

it('return loading=false, networkStatus and the data once the query resolved', async () => {
it('returns loading=false, networkStatus and the data once the query resolved', async () => {
function MockQuery({children}) {
const results = useQuery(petQuery);
return children(results);
Expand All @@ -120,6 +120,26 @@ describe('useQuery', () => {
);
});

it('calls onCompleted function when the query resolved', async () => {
const mockedOnCompleted = jest.fn();
function MockQuery({children}) {
const results = useQuery(petQuery, {
onCompleted: mockedOnCompleted,
});
return children(results);
}

const graphQL = createGraphQL({PetQuery: mockData});
const renderPropSpy = jest.fn(() => null);

await mountWithGraphQL(<MockQuery>{renderPropSpy}</MockQuery>, {
graphQL,
});

expect(mockedOnCompleted).toHaveBeenCalledTimes(1);
expect(mockedOnCompleted).toHaveBeenCalledWith(mockData);
});

it('keeps the same data when the variables stay deep-equal', async () => {
function MockQuery({
children,
Expand Down

0 comments on commit 444538a

Please sign in to comment.