Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

Ensure updateQuery is included in QueryResult with useLazyQuery #3583

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions packages/hooks/src/__tests__/useLazyQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -447,4 +447,65 @@ describe('useLazyQuery Hook', () => {
expect(renderCount).toBe(5);
});
});

it('should pass updateQuery in QueryResult', async () => {
const data1 = CAR_RESULT_DATA;
const data2 = {
cars: []
};
const mocks = [
{
request: {
query: CAR_QUERY
},
result: { data: data1 }
}
];

let renderCount = 0;
const Component = () => {
const [execute, { loading, data, updateQuery }] = useLazyQuery(
CAR_QUERY,
{
fetchPolicy: 'network-only'
}
);
switch (renderCount) {
case 0:
expect(updateQuery).toBeDefined();
expect(loading).toEqual(false);
setTimeout(() => {
execute();
});
break;
case 1:
expect(loading).toEqual(true);
break;
case 2:
expect(loading).toEqual(false);
expect(data).toEqual(data1);
setTimeout(() => {
updateQuery(() => data2);
});
break;
case 3:
expect(loading).toEqual(false);
expect(data).toEqual(data2);
break;
default: // Do nothing
}
renderCount += 1;
return null;
};

render(
<MockedProvider mocks={mocks}>
<Component />
</MockedProvider>
);

await wait(() => {
expect(renderCount).toBe(4);
});
});
});
16 changes: 15 additions & 1 deletion packages/hooks/src/data/QueryData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
QueryResult,
ObservableQueryFields
} from '@apollo/react-common';
import { invariant } from 'ts-invariant';

import {
QueryPreviousData,
Expand Down Expand Up @@ -69,7 +70,8 @@ export class QueryData<TData, TVariables> extends OperationData {
loading: false,
networkStatus: NetworkStatus.ready,
called: false,
data: undefined
data: undefined,
updateQuery: this.lazyUpdateQuery
} as QueryResult<TData, TVariables>
]
: [this.runLazyQuery, this.execute()];
Expand Down Expand Up @@ -487,4 +489,16 @@ export class QueryData<TData, TVariables> extends OperationData {
subscribeToMore: this.obsSubscribeToMore
} as ObservableQueryFields<TData, TVariables>;
}

private lazyUpdateQuery: QueryResult<
TData,
TVariables
>['updateQuery'] = mapFn => {
const { query } = this.currentObservable;
invariant(
query,
`updateQuery cannot be invoked if the lazy query was not executed first.`
);
return query!.updateQuery(mapFn);
};
}