Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support onCompleted callback on useQuery #2741

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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