diff --git a/src/cache/core/cache.ts b/src/cache/core/cache.ts index cb953152c45..21659404799 100644 --- a/src/cache/core/cache.ts +++ b/src/cache/core/cache.ts @@ -229,7 +229,16 @@ export abstract class ApolloCache implements DataProxy { const diffOptions: Cache.DiffOptions = { ...otherOptions, returnPartialData: true, - id: typeof from === "string" ? from : this.identify(from), + id: + // While our TypeScript types do not allow for `undefined` as a valid + // `from`, its possible `useFragment` gives us an `undefined` since it + // calls` cache.identify` and provides that value to `from`. We are + // adding this fix here however to ensure those using plain JavaScript + // and using `cache.identify` themselves will avoid seeing the obscure + // warning when passing `undefined` to `this.identify` below. + typeof from === "undefined" || typeof from === "string" ? + from + : this.identify(from), query, optimistic, }; diff --git a/src/react/hooks/__tests__/useFragment.test.tsx b/src/react/hooks/__tests__/useFragment.test.tsx index 046c1c538c9..378f48f9a4d 100644 --- a/src/react/hooks/__tests__/useFragment.test.tsx +++ b/src/react/hooks/__tests__/useFragment.test.tsx @@ -1725,6 +1725,34 @@ describe("useFragment", () => { }); }); }); + + // https://github.com/apollographql/apollo-client/issues/12051 + it("does not warn when the cache identifier is invalid", async () => { + using _ = spyOnConsole("warn"); + const cache = new InMemoryCache(); + + const ProfiledHook = profileHook(() => + useFragment({ + fragment: ItemFragment, + // Force a value that results in cache.identify === undefined + from: { __typename: "Item" }, + }) + ); + + render(, { + wrapper: ({ children }) => ( + {children} + ), + }); + + expect(console.warn).not.toHaveBeenCalled(); + + const { data, complete } = await ProfiledHook.takeSnapshot(); + + // TODO: Update when https://github.com/apollographql/apollo-client/issues/12003 is fixed + expect(complete).toBe(true); + expect(data).toEqual({}); + }); }); describe("has the same timing as `useQuery`", () => {