Minor Changes
-
#13132
f3ce805Thanks @phryneas! - Introduce "classic" and "modern" method and hook signatures.Apollo Client 4.2 introduces two signature styles for methods and hooks. All signatures previously present are now "classic" signatures, and a new set of "modern" signatures are added alongside them.
Classic signatures are the default and are identical to the signatures before Apollo Client 4.2, preserving backward compatibility. Classic signatures still work with manually specified TypeScript generics (e.g.,
useSuspenseQuery<MyData>(...)). However, manually specifying generics has been discouraged for a long time—instead, we recommend usingTypedDocumentNodeto automatically infer types, which provides more accurate results without any manual annotations.Modern signatures automatically incorporate your declared
defaultOptionsinto return types, providing more accurate types. Modern signatures infer types from the document node and do not support manually passing generic type arguments; TypeScript will produce a type error if you attempt to do so.Methods and hooks automatically switch to modern signatures the moment any non-optional property is declared in
DeclareDefaultOptions. The switch happens across all methods and hooks globally:// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { namespace ApolloClient { namespace DeclareDefaultOptions { interface WatchQuery { errorPolicy: "all"; // non-optional → modern signatures activated automatically } } } }
Users can also manually switch to modern signatures without declaring any
defaultOptions, for example when wanting accurate type inference without relying on globaldefaultOptions:// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { export interface TypeOverrides { signatureStyle: "modern"; } }
Users can do a global
DeclareDefaultOptionstype augmentation and then manually switch back to "classic" for migration purposes:// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { export interface TypeOverrides { signatureStyle: "classic"; } }
Note that this is not recommended for long-term use. When combined with
DeclareDefaultOptions, switching back to classic results in the same incorrect types as before Apollo Client 4.2—methods and hooks will not reflect thedefaultOptionsyou've declared. -
#13130
dd12231Thanks @jerelmiller! - Improve the accuracy ofclient.queryreturn type to better detect the currenterrorPolicy. Thedataproperty is no longer nullable when theerrorPolicyisnone. This makes it possible to remove theundefinedchecks or optional chaining in most cases. -
#13210
1f9a428Thanks @jerelmiller! - Add support for automatic event-based refetching, such as window focus.The
RefetchEventManagerclass handles automatic refetches in response to events. Apollo Client provides built-in sources for window focus and network reconnect aswindowFocusSourceandonlineSource.Event refetching is fully opt-in. Create and pass a
RefetchEventManagerinstance to theApolloClientconstructor to activate the event listeners.import { ApolloClient, InMemoryCache, RefetchEventManager, windowFocusSource, onlineSource, } from "@apollo/client"; const client = new ApolloClient({ link, cache: new InMemoryCache(), refetchEventManager: new RefetchEventManager({ sources: { // Refetch when window is focused windowFocus: windowFocusSource, // Refetch when the user comes back online online: onlineSource, }, }), });
By default, all active queries refetch when the events fire. Queries can opt out per-event or disable all event refetches:
// Skip refetch on window focus for this query, but keep `online` useQuery(QUERY, { refetchOn: { windowFocus: false }, }); // Disable all event-driven refetches for this query useQuery(OTHER_QUERY, { refetchOn: false, }); // Enable every event for this query, regardless of defaultOptions useQuery(LIVE_DASHBOARD, { refetchOn: true, }); // Dynamically enable or disable a refetch when the event fires useQuery(LIVE_DASHBOARD, { refetchOn: ({ source, payload }) => { if (source === "windowFocus") { // payload is the data associated with the event return someCondition(payload); } return true; }, }); // Dynamically enable or disable a refetch for a specific event useQuery(LIVE_DASHBOARD, { refetchOn: { windowFocus: ({ payload }) => { // payload is the data associated with the event return someCondition(payload); }, }, });
To enable per-query opt-in rather than opt-out, set
defaultOptions.watchQuery.refetchOntofalseand enable it per-query instead.const client = new ApolloClient({ link, cache, refetchEventManager: new RefetchEventManager({ sources: { windowFocus: windowFocusSource }, }), defaultOptions: { watchQuery: { refetchOn: false }, }, }); // Only this query refetches on window focus useQuery(DASHBOARD_QUERY, { refetchOn: { windowFocus: true } });
When
defaultOptions.watchQuery.refetchOnand per-queryrefetchOnoptions are provided, the objects are merged together.Custom events
You can also add your own custom events that trigger refetches. Register your event name and payload type using TypeScript module augmentation, then provide a source function that returns an Observable. The source's emitted value becomes the event's
payload.import { Observable } from "@apollo/client"; import { filter } from "rxjs"; import { AppState, AppStateStatus, Platform } from "react-native"; declare module "@apollo/client" { interface RefetchEvents { reactNativeAppStatus: AppStateStatus; } } const refetchEventManager = new RefetchEventManager({ sources: { reactNativeAppStatus: () => { return new Observable((observer) => { const subscription = AppState.addEventListener("change", (status) => { observer.next(status); }); return () => subscription.remove(); }).pipe( filter((status) => Platform.OS !== "web" && status === "active") ); }, }, }); // Disable per-query by setting the event to false useQuery(QUERY, { refetchOn: { reactNativeAppStatus: false } });
Manually trigger an event refetch
Refetches can be triggered imperatively by calling
emitwith the event name and its payload (if any).refetchEventManager.emit("reactNativeAppStatus", "active");
Sourceless events
A source that has no automatic detection logic but still wants imperative
emitsupport can be declared astrue. Type the event asvoidto omit the payload argument.declare module "@apollo/client" { interface RefetchEvents { userTriggered: void; } } const refetchEventManager = new RefetchEventManager({ sources: { userTriggered: true }, }); refetchEventManager.emit("userTriggered");
Note: Calling
emiton an event without a registered source will log a warning and result in a no-op.Custom handlers
When an event fires, the default handler calls
client.refetchQueries({ include: "active" })filtered by each query'srefetchOnsetting. You can override the handler for an event to add your own custom filtering. For example, to refetch all queries, includingstandbyqueries, define a handler for the event:const refetchEventManager = new RefetchEventManager({ // ... handlers: { userTriggered: ({ client, source, payload, matchesRefetchOn }) => { return client.refetchQueries({ include: "all", onQueryUpdated: (observableQuery) => { return matchesRefetchOn(observableQuery); }, }); }, }, });
Handlers must return either a
RefetchQueriesResultorvoid. Returningvoidskips refetching for the event. -
#13232
f1b541fThanks @jerelmiller! - Version bump torc. -
#13206
08fccabThanks @jerelmiller! - Extend thedefaultOptionstype-safety work toclient.mutateanduseMutation.The
errorPolicyoption now flows through to the result types for mutations in the same way it already does for queries:ApolloClient.MutateResult<TData, TErrorPolicy>mapserrorPolicyto the concrete shape ofdataanderror:"none"→{ data: TData; error?: never }"all"→{ data: TData | undefined; error?: ErrorLike }"ignore"→{ data: TData | undefined; error?: never }
client.mutateanduseMutationpick up the declareddefaultOptions.mutate.errorPolicyand the expliciterrorPolicyon each call to narrow return types accordingly.useMutation.Result.erroris narrowed toundefinedwhenerrorPolicyis"ignore", sinceclient.mutatenever resolves with an error in that case.
DeclareDefaultOptions.Mutatealready acceptederrorPolicy; the new behavior is that once you declare it, hook and method return types reflect it:// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { namespace ApolloClient { namespace DeclareDefaultOptions { interface Mutate { errorPolicy: "all"; } } } }
const result = await client.mutate({ mutation: MUTATION }); result.data; // ^? TData | undefined result.error; // ^? ErrorLike | undefined
Setting
errorPolicyon an individual call overrides the default for that call's return type. -
#13222
b93c172Thanks @jerelmiller! - Extend thedefaultOptionstype-safety work topreloadQuery(returned fromcreateQueryPreloader). Defaults declared inDeclareDefaultOptions.WatchQuerynow work withpreloadQueryto ensure thePreloadedQueryRef's data states are correctly set.// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { namespace ApolloClient { namespace DeclareDefaultOptions { interface WatchQuery { errorPolicy: "all"; } } } }
const preloadQuery = createQueryPreloader(client); const queryRef = preloadQuery(QUERY); // ^? PreloadedQueryRef<TData, TVariables, "complete" | "streaming" | "empty">
-
#13132
f3ce805Thanks @phryneas! - Synchronize method and hook return types withdefaultOptions.Prior to this change, the following code snippet would always apply:
declare const MY_QUERY: TypedDocumentNode<TData, TVariables>; const result1 = useSuspenseQuery(MY_QUERY); result1.data; // ^? TData const result2 = useSuspenseQuery(MY_QUERY, { errorPolicy: "all" }); result2.data; // ^? TData | undefined
While these types are generally correct, if you were to set
errorPolicy: 'all'as a default option, the type ofresult.datafor the first query would remainTDatainstead of changing toTData | undefinedto match the runtime behavior.We are now enforcing that certain
defaultOptionstypes need to be registered globally. This means that if you want to useerrorPolicy: 'all'as a default option for a query, you will need to register its type like this:// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { namespace ApolloClient { namespace DeclareDefaultOptions { interface WatchQuery { // possible global-registered values: // * `errorPolicy` // * `returnPartialData` errorPolicy: "all"; } interface Query { // possible global-registered values: // * `errorPolicy` } interface Mutate { // possible global-registered values: // * `errorPolicy` } } } }
Once this type declaration is in place, the type of
result.datain the above example will correctly be changed toTData | undefined, reflecting the possibility that if an error occurs,datamight beundefined. Manually specifyinguseSuspenseQuery(MY_QUERY, { errorPolicy: "none" });changesresult.datatoTDatato reflect the local override.This change means that you will need to declare your default options types in order to use
defaultOptionswithApolloClient, otherwise you will see a TypeScript error.Without the type declaration, the following (previously valid) code will now error:
new ApolloClient({ link: ApolloLink.empty(), cache: new InMemoryCache(), defaultOptions: { watchQuery: { // results in a type error: // Type '"all"' is not assignable to type '"A default option for watchQuery.errorPolicy must be declared in ApolloClient.DeclareDefaultOptions before usage. See https://www.apollographql.com/docs/react/data/typescript#declaring-default-options-for-type-safety."'. errorPolicy: "all", }, }, });
If you are creating multiple instances of Apollo Client with conflicting default options and you cannot register a single
defaultOptionsvalue as a result, you can relax the constraints by declaring those options as union types covering all values used by all clients. The properties can be required (to enforce them indefaultOptions) or optional (if some constructor calls won't pass a value):// apollo.d.ts import "@apollo/client"; declare module "@apollo/client" { export namespace ApolloClient { export namespace DeclareDefaultOptions { interface WatchQuery { errorPolicy?: "none" | "all" | "ignore"; returnPartialData?: boolean; } interface Query { errorPolicy?: "none" | "all" | "ignore"; } interface Mutate { errorPolicy?: "none" | "all" | "ignore"; } } } }
With this declaration, the
ApolloClientconstructor accepts any of those values indefaultOptions. The tradeoff is that hook and method return types become more generic. For example, callinguseSuspenseQuerywithout an expliciterrorPolicywill return a result typed as if all error policies are possible, since TypeScript can't know which specific value your instance uses at runtime.Note that making a property optional (
errorPolicy?:) is equivalent to adding the TypeScript default value ("none") to the union. SoerrorPolicy?: "all" | "ignore"has the same effect on return types aserrorPolicy: "none" | "all" | "ignore", because TypeScript assumes the option could also be absent (i.e.,"none").You can also use a partial union that only lists the values you actually use. For example, if you only ever use
"all"or"ignore", declareerrorPolicy: "all" | "ignore"(required) to keep the union narrow and avoid unused values broadening your signatures unnecessarily.
Patch Changes
-
#13217
790f987Thanks @jerelmiller! - Fix the deprecation for the classic signatures for function overloads that rely on type inference from aTypedDocumentNode. The deprecation now only applies to classic signatures that provide explicit type arguments to encourage the use ofTypedDocumentNode. -
#13166
0537d97Thanks @jerelmiller! - Release changes in 4.1.5 and 4.1.6. -
#13215
54c9eb7Thanks @jerelmiller! - Ensure the options object for theuseQuery,useSuspenseQuery, anduseBackgroundQueryhooks provide proper IntelliSense suggestions. -
#13229
9a7f65aThanks @jerelmiller! - FixrefetchOnmerging whendefaultOptions.watchQuery.refetchOnis set to a non-object value (false,true, or a function) and the per-queryrefetchOnis an object. Previously the per-query object completely replaced the default so unspecified events fell back to "enabled" regardless of the default.The
defaultOptionsvalue now applies to any event the per-query object does not explicitly configure:false- unspecified events stay disabledtrue- unspecified events refetch- Callback function - the function is called for unspecified events to determine whether to refetch
const client = new ApolloClient({ // ... defaultOptions: { watchQuery: { refetchOn: false, }, }, }); // Only `windowFocus` refetches. Other events stay disabled per the default. useQuery(QUERY, { refetchOn: { windowFocus: true } });
-
#13230
b25b659Thanks @jerelmiller! - Add the ability to override the default event handler onRefetchEventManager. The default handler runs when no per-source handler is configured for an event. Provide a custom handler via thedefaultHandlerconstructor option or thesetDefaultEventHandlerinstance method.new RefetchEventManager({ defaultHandler: ({ client, matchesRefetchOn }) => { return client.refetchQueries({ include: "all", onQueryUpdated: matchesRefetchOn, }); }, });