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

Fix issue where an empty array returned from fetchMore would rerender with an empty list #11706

Merged
merged 7 commits into from
Mar 20, 2024
Merged
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
5 changes: 5 additions & 0 deletions .changeset/curly-berries-hammer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@apollo/client": patch
---

Fix issue in all suspense hooks where returning an empty array after calling `fetchMore` would rerender the component with an empty list.
2 changes: 1 addition & 1 deletion .size-limits.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"dist/apollo-client.min.cjs": 39267,
"dist/apollo-client.min.cjs": 39273,
"import { ApolloClient, InMemoryCache, HttpLink } from \"dist/index.js\" (production)": 32630
}
11 changes: 10 additions & 1 deletion src/react/hooks/__tests__/useBackgroundQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4795,6 +4795,15 @@ describe("refetch", () => {
describe("fetchMore", () => {
it("re-suspends when calling `fetchMore` with different variables", async () => {
const { query, link } = setupPaginatedCase();
const cache = new InMemoryCache({
typePolicies: {
Copy link
Member Author

Choose a reason for hiding this comment

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

Turns out these type policies were needed all along in some of these tests. The bug that this PR fixes masked this issue which is why these wasn't originally part of these tests.

Query: {
fields: {
letters: { keyArgs: false },
},
},
},
});
const user = userEvent.setup();
const Profiler = createDefaultProfiler<PaginatedCaseData>();
const { SuspenseFallback, ReadQueryHook } =
Expand All @@ -4818,7 +4827,7 @@ describe("fetchMore", () => {
);
}

renderWithMocks(<App />, { link, wrapper: Profiler });
renderWithMocks(<App />, { cache, link, wrapper: Profiler });

{
const { renderedComponents } = await Profiler.takeRender();
Expand Down
26 changes: 21 additions & 5 deletions src/react/hooks/__tests__/useLoadableQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
Profiler,
SimpleCaseData,
createProfiler,
setupPaginatedCase,
setupSimpleCase,
spyOnConsole,
useTrackRenders,
Expand Down Expand Up @@ -3205,7 +3206,22 @@ it("`refetch` works with startTransition to allow React to show stale UI until f
});

it("re-suspends when calling `fetchMore` with different variables", async () => {
const { query, client } = usePaginatedQueryCase();
const { query, link } = setupPaginatedCase();

const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: {
keyArgs: false,
},
},
},
},
}),
});

const Profiler = createDefaultProfiler<PaginatedQueryData>();
const { SuspenseFallback, ReadQueryHook } =
Expand Down Expand Up @@ -3244,8 +3260,8 @@ it("re-suspends when calling `fetchMore` with different variables", async () =>
expect(snapshot.result).toEqual({
data: {
letters: [
{ letter: "A", position: 1 },
{ letter: "B", position: 2 },
{ __typename: "Letter", letter: "A", position: 1 },
{ __typename: "Letter", letter: "B", position: 2 },
],
},
error: undefined,
Expand All @@ -3268,8 +3284,8 @@ it("re-suspends when calling `fetchMore` with different variables", async () =>
expect(snapshot.result).toEqual({
data: {
letters: [
{ letter: "C", position: 3 },
{ letter: "D", position: 4 },
{ __typename: "Letter", letter: "C", position: 3 },
{ __typename: "Letter", letter: "D", position: 4 },
],
},
error: undefined,
Expand Down
65 changes: 60 additions & 5 deletions src/react/hooks/__tests__/useQueryRefHandlers.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1100,7 +1100,18 @@ test("resuspends when calling `fetchMore`", async () => {

const user = userEvent.setup();

const client = new ApolloClient({ cache: new InMemoryCache(), link });
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: { keyArgs: false },
},
},
},
}),
link,
});
const preloadQuery = createQueryPreloader(client);

const Profiler = createProfiler({
Expand Down Expand Up @@ -1397,7 +1408,18 @@ test("paginates from queryRefs produced by useBackgroundQuery", async () => {
const { query, link } = setupPaginatedCase();

const user = userEvent.setup();
const client = new ApolloClient({ cache: new InMemoryCache(), link });
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: { keyArgs: false },
},
},
},
}),
link,
});

const Profiler = createProfiler({
initialSnapshot: {
Expand Down Expand Up @@ -1489,7 +1511,18 @@ test("paginates from queryRefs produced by useLoadableQuery", async () => {
const { query, link } = setupPaginatedCase();

const user = userEvent.setup();
const client = new ApolloClient({ cache: new InMemoryCache(), link });
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: { keyArgs: false },
},
},
},
}),
link,
});

const Profiler = createProfiler({
initialSnapshot: {
Expand Down Expand Up @@ -1589,7 +1622,18 @@ test("`fetchMore` works with startTransition", async () => {
const { query, link } = setupPaginatedCase();

const user = userEvent.setup();
const client = new ApolloClient({ cache: new InMemoryCache(), link });
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: { keyArgs: false },
},
},
},
}),
link,
});
const preloadQuery = createQueryPreloader(client);

const Profiler = createProfiler({
Expand Down Expand Up @@ -1708,7 +1752,18 @@ test("`fetchMore` works with startTransition from useBackgroundQuery and useQuer
const { query, link } = setupPaginatedCase();

const user = userEvent.setup();
const client = new ApolloClient({ cache: new InMemoryCache(), link });
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: { keyArgs: false },
},
},
},
}),
link,
});

const Profiler = createProfiler({
initialSnapshot: {
Expand Down
144 changes: 144 additions & 0 deletions src/react/hooks/__tests__/useSuspenseQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10109,6 +10109,150 @@ describe("useSuspenseQuery", () => {
await expect(Profiler).not.toRerender();
});

// https://github.com/apollographql/apollo-client/issues/11642
it("returns merged array when `fetchMore` returns empty array of results", async () => {
const query: TypedDocumentNode<PaginatedCaseData, PaginatedCaseVariables> =
gql`
query LettersQuery($limit: Int, $offset: Int) {
letters(limit: $limit, offset: $offset) {
letter
position
}
}
`;

const data = "ABCD".split("").map((letter, index) => ({
__typename: "Letter",
letter,
position: index + 1,
}));

const link = new MockLink([
{
request: { query, variables: { offset: 0, limit: 2 } },
result: { data: { letters: data.slice(0, 2) } },
delay: 20,
},
{
request: { query, variables: { offset: 2, limit: 2 } },
result: { data: { letters: data.slice(2, 4) } },
delay: 20,
},
{
request: { query, variables: { offset: 4, limit: 2 } },
result: { data: { letters: [] } },
delay: 20,
},
]);

const user = userEvent.setup();
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
letters: offsetLimitPagination(),
},
},
},
}),
link,
});

const Profiler = createProfiler({
initialSnapshot: {
result: null as UseSuspenseQueryResult<
PaginatedCaseData,
PaginatedCaseVariables
> | null,
},
});

function App() {
useTrackRenders();
const result = useSuspenseQuery(query, {
variables: { offset: 0, limit: 2 },
});
const { data, fetchMore } = result;

Profiler.mergeSnapshot({ result });

return (
<button
onClick={() =>
fetchMore({
variables: {
offset: data.letters.length,
limit: 2,
},
})
}
>
Fetch next
</button>
);
}

render(<App />, {
wrapper: ({ children }) => (
<ApolloProvider client={client}>
<Profiler>
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</Profiler>
</ApolloProvider>
),
});

// initial suspended render
await Profiler.takeRender();

{
const { snapshot, renderedComponents } = await Profiler.takeRender();

expect(renderedComponents).toStrictEqual([App]);
expect(snapshot.result?.data).toEqual({
letters: [
{ __typename: "Letter", letter: "A", position: 1 },
{ __typename: "Letter", letter: "B", position: 2 },
],
});
}

await act(() => user.click(screen.getByText("Fetch next")));
await Profiler.takeRender();

{
const { snapshot } = await Profiler.takeRender();

expect(snapshot.result?.data).toEqual({
letters: [
{ __typename: "Letter", letter: "A", position: 1 },
{ __typename: "Letter", letter: "B", position: 2 },
{ __typename: "Letter", letter: "C", position: 3 },
{ __typename: "Letter", letter: "D", position: 4 },
],
});
}

await act(() => user.click(screen.getByText("Fetch next")));
await Profiler.takeRender();

{
const { snapshot } = await Profiler.takeRender();

expect(snapshot.result?.data).toEqual({
letters: [
{ __typename: "Letter", letter: "A", position: 1 },
{ __typename: "Letter", letter: "B", position: 2 },
{ __typename: "Letter", letter: "C", position: 3 },
{ __typename: "Letter", letter: "D", position: 4 },
],
});
}

await expect(Profiler).not.toRerender();
});

describe.skip("type tests", () => {
it("returns unknown when TData cannot be inferred", () => {
const query = gql`
Expand Down
14 changes: 11 additions & 3 deletions src/react/internal/cache/QueryReference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ export class InternalQueryReference<TData = unknown> {
// to resolve the promise if `handleNext` hasn't been run to ensure the
// promise is resolved correctly.
returnedPromise
.then((result) => {
.then(() => {
// In the case of `fetchMore`, this promise is resolved before a cache
// result is emitted due to the fact that `fetchMore` sets a `no-cache`
// fetch policy and runs `cache.batch` in its `.then` handler. Because
Expand All @@ -390,8 +390,16 @@ export class InternalQueryReference<TData = unknown> {
// more information
setTimeout(() => {
if (this.promise.status === "pending") {
this.result = result;
this.resolve?.(result);
// Use the current result from the observable instead of the value
// resolved from the promise. This avoids issues in some cases where
// the raw resolved value should not be the emitted value, such as
// when a `fetchMore` call returns an empty array after it has
// reached the end of the list.
//
// See the following for more information:
// https://github.com/apollographql/apollo-client/issues/11642
this.result = this.observable.getCurrentResult();
this.resolve?.(this.result);
}
});
})
Expand Down
Loading