Skip to content

Commit

Permalink
Showing 3 changed files with 62 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/little-schools-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@apollo/client': patch
---

Fix a bug in `QueryReference` where `this.resolve` or `this.reject` might be executed even if `undefined`.
12 changes: 8 additions & 4 deletions src/react/cache/QueryReference.ts
Original file line number Diff line number Diff line change
@@ -36,8 +36,8 @@ export class QueryReference<TData = unknown> {
private initialized = false;
private refetching = false;

private resolve: (result: ApolloQueryResult<TData>) => void;
private reject: (error: unknown) => void;
private resolve: ((result: ApolloQueryResult<TData>) => void) | undefined;
private reject: ((error: unknown) => void) | undefined;

constructor(
observable: ObservableQuery<TData>,
@@ -157,7 +157,9 @@ export class QueryReference<TData = unknown> {
this.initialized = true;
this.refetching = false;
this.result = result;
this.resolve(result);
if (this.resolve) {
this.resolve(result);
}
return;
}

@@ -182,7 +184,9 @@ export class QueryReference<TData = unknown> {
if (!this.initialized || this.refetching) {
this.initialized = true;
this.refetching = false;
this.reject(error);
if (this.reject) {
this.reject(error);
}
return;
}

49 changes: 49 additions & 0 deletions src/react/hooks/__tests__/useSuspenseQuery.test.tsx
Original file line number Diff line number Diff line change
@@ -4408,6 +4408,55 @@ describe('useSuspenseQuery', () => {
]);
});

it('suspends when refetching after returning cached data for the initial fetch', async () => {
const { query, mocks } = useSimpleQueryCase();

const cache = new InMemoryCache();

cache.writeQuery({
query,
data: { greeting: 'hello from cache' },
});

const { result, renders } = renderSuspenseHook(
() => useSuspenseQuery(query),
{ cache, mocks }
);

expect(result.current).toMatchObject({
data: { greeting: 'hello from cache' },
networkStatus: NetworkStatus.ready,
error: undefined,
});

act(() => {
result.current.refetch();
});

await waitFor(() => {
expect(result.current).toMatchObject({
data: { greeting: 'Hello' },
networkStatus: NetworkStatus.ready,
error: undefined,
});
});

expect(renders.count).toBe(3);
expect(renders.suspenseCount).toBe(1);
expect(renders.frames).toMatchObject([
{
data: { greeting: 'hello from cache' },
networkStatus: NetworkStatus.ready,
error: undefined,
},
{
data: { greeting: 'Hello' },
networkStatus: NetworkStatus.ready,
error: undefined,
},
]);
});

it('properly uses `updateQuery` when calling `fetchMore`', async () => {
const { data, query, link } = usePaginatedCase();

0 comments on commit c1904a7

Please sign in to comment.