339 KiB
@apollo/client
3.13.8
Patch Changes
- #12567
c19d415Thanks @thearchitector! - Fix in-flight multipart urql subscription cancellation
3.13.7
Patch Changes
-
#12540
0098932Thanks @phryneas! - Refactor: Move notification scheduling logic fromQueryInfotoObservableQuery -
#12540
0098932Thanks @phryneas! - Refactored cache emit logic for ObservableQuery. This should be an invisible change.
3.13.6
Patch Changes
- #12285
cdc55ffThanks @phryneas! - keep ObservableQuery created by useQuery non-active before it is first subscribed
3.13.5
Patch Changes
- #12461
12c8d06Thanks @jerelmiller! - Fix an issue where acache-firstquery would return the result for previous variables when a cache update is issued after simultaneously changing variables and skipping the query.
3.13.4
Patch Changes
- #12420
fee9368Thanks @jorenbroekema! - Use import star fromrehacktto prevent issues with importing named exports from external CJS modules.
3.13.3
Patch Changes
-
#12362
f6d387cThanks @jerelmiller! - Fixes an issue where callingobservableQuery.getCurrentResult()when theerrorPolicywas set toallwould return thenetworkStatusasNetworkStatus.readywhen there were errors returned in the result. This has been corrected to reportNetworkStatus.error.This bug also affected the
useQueryanduseLazyQueryhooks and may affect you if you check fornetworkStatusin your component.
3.13.2
Patch Changes
-
#12409
6aa2f3eThanks @phryneas! - To mitigate problems when Apollo Client ends up more than once in the bundle, some unique symbols were converted intoSymbol.forcalls. -
#12392
644bb26Thanks @Joja81! - Fixes an issue where the DeepOmit type would turn optional properties into required properties. This should only affect you if you were using the omitDeep or stripTypename utilities exported by Apollo Client. -
#12404
4332b88Thanks @jerelmiller! - ShowNaNrather than converting tonullin debug messages fromMockLinkfor unmatchedvariablesvalues.
3.13.1
Patch Changes
-
#12369
bdfc5b2Thanks @phryneas! -ObervableQuery.refetch: don't refetch withcache-and-network, swich tonetwork-onlyinstead -
#12375
d3f8f13Thanks @jerelmiller! - Export theUseSuspenseFragmentOptionstype.
3.13.0
Minor Changes
-
#12066
c01da5dThanks @jerelmiller! - Adds a newuseSuspenseFragmenthook.useSuspenseFragmentsuspends untildatais complete. It is a drop-in replacement foruseFragmentwhen you prefer to use Suspense to control the loading state of a fragment. See the documentation for more details. -
#12174
ba5cc33Thanks @jerelmiller! - Ensure errors thrown in theonCompletedcallback fromuseMutationdon't callonError. -
#12340
716d02eThanks @phryneas! - Deprecate theonCompletedandonErrorcallbacks ofuseQueryanduseLazyQuery. For more context, please see the related issue on GitHub. -
#12276
670f112Thanks @Cellule! - Provide a more type-safe option for the previous data value passed toobservableQuery.updateQuery. Using it could result in crashes at runtime as this callback could be called with partial data even though its type reported the value as a complete result.The
updateQuerycallback function is now called with a new type-safepreviousDataproperty and a newcompleteproperty in the 2nd argument that determines whetherpreviousDatais a complete or partial result.As a result of this change, it is recommended to use the
previousDataproperty passed to the 2nd argument of the callback rather than using the previous data value from the first argument since that value is not type-safe. The first argument is now deprecated and will be removed in a future version of Apollo Client.observableQuery.updateQuery( (unsafePreviousData, { previousData, complete }) => { previousData; // ^? TData | DeepPartial<TData> | undefined if (complete) { previousData; // ^? TData } else { previousData; // ^? DeepPartial<TData> | undefined } } ); -
#12174
ba5cc33Thanks @jerelmiller! - Reject the mutation promise if errors are thrown in theonCompletedcallback ofuseMutation.
Patch Changes
-
#12276
670f112Thanks @Cellule! - Fix the return type of theupdateQueryfunction to allow forundefined.updateQueryhad the ability to bail out of the update by returning a falsey value, but the return type enforced a query value.observableQuery.updateQuery( (unsafePreviousData, { previousData, complete }) => { if (!complete) { // Bail out of the update by returning early return; } // ... } ); -
#12296
2422df2Thanks @Cellule! - Deprecate optionignoreResultsinuseMutation. Once this option is removed, existing code still using it might see increase in re-renders. If you don't want to synchronize your component state with the mutation, please useuseApolloClientto get your ApolloClient instance and callclient.mutatedirectly. -
#12338
67c16c9Thanks @phryneas! - In case of a multipart response (e.g. with@defer), query deduplication will now keep going until the final chunk has been received. -
#12276
670f112Thanks @Cellule! - Fix the type of thevariablesproperty passed as the 2nd argument to thesubscribeToMorecallback. This was previously reported as thevariablestype for the subscription itself, but is now properly typed as the queryvariables.
3.13.0-rc.0
Minor Changes
-
#12066
c01da5dThanks @jerelmiller! - Adds a newuseSuspenseFragmenthook.useSuspenseFragmentsuspends untildatais complete. It is a drop-in replacement foruseFragmentwhen you prefer to use Suspense to control the loading state of a fragment. -
#12174
ba5cc33Thanks @jerelmiller! - Ensure errors thrown in theonCompletedcallback fromuseMutationdon't callonError. -
#12340
716d02eThanks @phryneas! - Deprecate theonCompletedandonErrorcallbacks ofuseQueryanduseLazyQuery. For more context, please see the related issue on GitHub. -
#12276
670f112Thanks @Cellule! - Provide a more type-safe option for the previous data value passed toobservableQuery.updateQuery. Using it could result in crashes at runtime as this callback could be called with partial data even though its type reported the value as a complete result.The
updateQuerycallback function is now called with a new type-safepreviousDataproperty and a newcompleteproperty in the 2nd argument that determines whetherpreviousDatais a complete or partial result.As a result of this change, it is recommended to use the
previousDataproperty passed to the 2nd argument of the callback rather than using the previous data value from the first argument since that value is not type-safe. The first argument is now deprecated and will be removed in a future version of Apollo Client.observableQuery.updateQuery( (unsafePreviousData, { previousData, complete }) => { previousData; // ^? TData | DeepPartial<TData> | undefined if (complete) { previousData; // ^? TData } else { previousData; // ^? DeepPartial<TData> | undefined } } ); -
#12174
ba5cc33Thanks @jerelmiller! - Reject the mutation promise if errors are thrown in theonCompletedcallback ofuseMutation.
Patch Changes
-
#12276
670f112Thanks @Cellule! - Fix the return type of theupdateQueryfunction to allow forundefined.updateQueryhad the ability to bail out of the update by returning a falsey value, but the return type enforced a query value.observableQuery.updateQuery( (unsafePreviousData, { previousData, complete }) => { if (!complete) { // Bail out of the update by returning early return; } // ... } ); -
#12296
2422df2Thanks @Cellule! - Deprecate optionignoreResultsinuseMutation. Once this option is removed, existing code still using it might see increase in re-renders. If you don't want to synchronize your component state with the mutation, please useuseApolloClientto get your ApolloClient instance and callclient.mutatedirectly. -
#12338
67c16c9Thanks @phryneas! - In case of a multipart response (e.g. with@defer), query deduplication will now keep going until the final chunk has been received. -
#12276
670f112Thanks @Cellule! - Fix the type of thevariablesproperty passed as the 2nd argument to thesubscribeToMoreupdateQuerycallback. This was previously reported as thevariablestype for the subscription itself, but is now properly typed as the queryvariables.
3.12.11
Patch Changes
-
#12351
3da908bThanks @jerelmiller! - Fixes an issue where the wrongnetworkStatusandloadingvalue was emitted fromobservableQuerywhen callingfetchMorewith ano-cachefetch policy. ThenetworkStatusnow properly reports asreadyandloadingasfalseafter the result is returned. -
#12354
a24ef94Thanks @phryneas! - Fix missingmain.d.ctsfile
3.12.10
Patch Changes
-
#12341
f2bb0b9Thanks @phryneas! -useReadQuery/useQueryRefHandlers: Fix a "hook order" warning that might be emitted in React 19 dev mode. -
#12342
219b26bThanks @phryneas! - Addgraphql-ws^6.0.3as a validpeerDependency
3.12.9
Patch Changes
-
#12321
daa4f33Thanks @jerelmiller! - Fix type ofextensionsinprotocolErrorsforApolloErrorand theonErrorlink. According to the multipart HTTP subscription protocol, fatal tranport errors follow the GraphQL error format which requireextensionsto be a map as its value instead of an array. -
#12318
b17968bThanks @jerelmiller! - AllowRetryLinkto retry an operation when fatal transport-level errors are emitted from multipart subscriptions.const retryLink = new RetryLink({ attempts: (count, operation, error) => { if (error instanceof ApolloError) { // errors available on the `protocolErrors` field in `ApolloError` console.log(error.protocolErrors); } return true; }, });
3.12.8
Patch Changes
-
#12292
3abd944Thanks @phryneas! - Remove unused dependencyresponse-iterator -
#12287
bf313a3Thanks @phryneas! - Fixes an issue whereclient.watchFragment/useFragmentwith@includescrashes when a separate cache update writes to the conditionally included fields.
3.12.7
Patch Changes
-
#12281
d638ec3Thanks @jerelmiller! - Make fatal tranport-level errors from multipart subscriptions available to the error link with theprotocolErrorsproperty.const errorLink = onError(({ protocolErrors }) => { if (protocolErrors) { console.log(protocolErrors); } }); -
#12281
d638ec3Thanks @jerelmiller! - Fix the array type for theerrorsfield on theApolloPayloadResulttype. This type was always in the shape of the GraphQL error format, per the multipart subscriptions protocol and never a plain string or a JavaScript error object.
3.12.6
Patch Changes
-
#12267
d57429dThanks @jerelmiller! - Maintain theTDatatype when used withUnmaskedwhenTDatais not a masked type generated from GraphQL Codegen. -
#12270
3601246Thanks @jerelmiller! - Fix handling of tagged/branded primitive types when used as scalar values withUnmasked.
3.12.5
Patch Changes
-
#12252
cb9cd4eThanks @jerelmiller! - Changes the default behavior of theMaybeMaskedtype to preserve types unless otherwise specified. This change makes it easier to upgrade from older versions of the client where types could have unexpectedly changed in the application due to the default of trying to unwrap types into unmasked types. This change also fixes the compilation performance regression experienced when simply upgrading the client since types are now preserved by default.A new
modeoption has now been introduced to allow for the old behavior. See the next section on migrating if you wish to maintain the old default behavior after upgrading to this version.Migrating from <= v3.12.4
If you've adopted data masking and have opted in to using masked types by setting the
enabledproperty totrue, you can remove this configuration entirely:-declare module "@apollo/client" { - interface DataMasking { - mode: "unmask" - } -}If you prefer to specify the behavior explicitly, change the property from
enabled: true, tomode: "preserveTypes":declare module "@apollo/client" { interface DataMasking { - enabled: true + mode: "preserveTypes" } }If you rely on the default behavior in 3.12.4 or below and would like to continue to use unmasked types by default, set the
modetounmask:declare module "@apollo/client" { interface DataMasking { mode: "unmask"; } }
3.12.4
Patch Changes
- #12236
4334d30Thanks @charpeni! - Fix an issue withrefetchQuerieswhere comparingDocumentNodes internally by references could lead to an unknown query, even though theDocumentNodewas indeed an active query—with a different reference.
3.12.3
Patch Changes
-
#12214
8bfee88Thanks @phryneas! - Data masking: prevent infinite recursion ofContainsFragmentsRefstype -
#12204
851deb0Thanks @jerelmiller! - FixUnmaskedunwrapping tuple types into an array of their subtypes. -
#12204
851deb0Thanks @jerelmiller! - EnsureMaybeMaskeddoes not try and unwrap types that contain index signatures. -
#12204
851deb0Thanks @jerelmiller! - EnsureMaybeMaskeddoes not try to unwrap the type asUnmaskedif the type containsany.
3.12.2
Patch Changes
- #12175
84af347Thanks @jerelmiller! - Update peer deps to allow for React 19 stable release.
3.12.1
Patch Changes
3.12.0
Minor Changes
Data masking 🎭
-
#12042
1c0ecbfThanks @jerelmiller! - Introduces data masking in Apollo Client.Data masking enforces that only the fields requested by the query or fragment is available to that component. Data masking is best paired with colocated fragments.
To enable data masking in Apollo Client, set the
dataMaskingoption totrue.new ApolloClient({ dataMasking: true, // ... other options });For detailed information on data masking, including how to incrementally adopt it in an existing applications, see the data masking documentation.
-
#12131
21c3f08Thanks @jerelmiller! - Allownullas a validfromvalue inuseFragment.
More Patch Changes
-
#12126
d10d702Thanks @jerelmiller! - Maintain the existing document if its unchanged by the codemod and move to more naive whitespace formatting -
#12150
9ed1e1eThanks @jerelmiller! - Fix issue when usingUnmaskedwith older versions of TypeScript when used with array fields. -
#12116
8ae6e4eThanks @jerelmiller! - Prevent field accessor warnings when using@unmask(mode: "migrate")on objects that are passed intocache.identify. -
#12120
6a98e76Thanks @jerelmiller! - Provide a codemod that applies@unmaskto all named fragments for all operations and fragments.Learn how to use the codemod in the incremental adoption documentation.
-
#12134
cfaf4efThanks @jerelmiller! - Fix issue where data went missing when an unmasked fragment in migrate mode selected fields that the parent did not. -
#12154
d933defThanks @phryneas! - Data masking types: handle overlapping nested array types and fragments on interface types. -
#12139
5a53e15Thanks @phryneas! - Fix issue where masked data would sometimes get returned when the field was part of a child fragment from a fragment unmasked by the parent query. -
#12123
8422a30Thanks @jerelmiller! - Warn when using data masking with "no-cache" operations. -
#12139
5a53e15Thanks @phryneas! - Fix issue where the warning emitted by@unmask(mode: "migrate")would trigger unnecessarily when the fragment was used alongside a masked fragment inside an inline fragment. -
#12114
1d4ce00Thanks @jerelmiller! - Fix error when combining@unmaskand@deferdirectives on a fragment spread when data masking is enabled. -
#12130
1e7d009Thanks @jerelmiller! - Fix error thrown when applying unmask migrate mode warnings on interface types with selection sets that contain inline fragment conditions. -
#12152
78137ecThanks @phryneas! - Add a helper that will skip the TS unmasking alorithm when no fragments are present on type level -
#12126
d10d702Thanks @jerelmiller! - Ensure documents unchanged by the codemod are left untouched. -
#12133
a6ece37Thanks @jerelmiller! - Ensurenullis retained in nullable types when unmasking a type with theUnmaskedhelper type. -
#12139
5a53e15Thanks @phryneas! - Fix issue that threw errors when masking partial data with@unmask(mode: "migrate").
3.12.0-rc.4
Patch Changes
- #12154
d933defThanks @phryneas! - Data masking types: handle overlapping nested array types and fragments on interface types.
3.12.0-rc.3
Patch Changes
-
#12150
9ed1e1eThanks @jerelmiller! - Fix issue when usingUnmaskedwith older versions of TypeScript when used with array fields. -
#12152
78137ecThanks @phryneas! - Add a helper that will skip the TS unmasking alorithm when no fragments are present on type level
3.12.0-rc.2
Patch Changes
-
#12139
5a53e15Thanks @phryneas! - Fix issue where masked data would sometimes get returned when the field was part of a child fragment from a fragment unmasked by the parent query. -
#12139
5a53e15Thanks @phryneas! - Fix issue where the warning emitted by@unmask(mode: "migrate")would trigger unnecessarily when the fragment was used alongside a masked fragment inside an inline fragment. -
#12139
5a53e15Thanks @phryneas! - Fix issue that threw errors when masking partial data with@unmask(mode: "migrate").
3.12.0-rc.1
Minor Changes
- #12131
21c3f08Thanks @jerelmiller! - Allownullas a validfromvalue inuseFragment.
Patch Changes
-
#12126
d10d702Thanks @jerelmiller! - Maintain the existing document if its unchanged by the codemod and move to more naive whitespace formatting -
#12134
cfaf4efThanks @jerelmiller! - Fix issue where data went missing when an unmasked fragment in migrate mode selected fields that the parent did not. -
#12130
1e7d009Thanks @jerelmiller! - Fix error thrown when applying unmask migrate mode warnings on interface types with selection sets that contain inline fragment conditions. -
#12126
d10d702Thanks @jerelmiller! - Ensure documents unchanged by the codemod are left untouched. -
#12133
a6ece37Thanks @jerelmiller! - Ensurenullis retained in nullable types when unmasking a type with theUnmaskedhelper type.
3.12.0-rc.0
Patch Changes
-
#12116
8ae6e4eThanks @jerelmiller! - Prevent field accessor warnings when using@unmask(mode: "migrate")on objects that are passed intocache.identify. -
#12120
6a98e76Thanks @jerelmiller! - Provide a codemod that applies@unmaskto all named fragments for all operations and fragments. To use the codemod, run the following command:npx jscodeshift -t node_modules/@apollo/client/scripts/codemods/data-masking/unmask.ts --extensions tsx --parser tsx path/to/app/To customize the tag used to search for GraphQL operations, use the
--tagoption. By default the codemod looks forgqlandgraphqltags.To apply the directive in migrate mode in order to receive runtime warnings on potentially masked fields, use the
--mode migrateoption.For more information on the options that can be used with
jscodeshift, check out thejscodeshiftdocumentation. -
#12121
1085a95Thanks @jerelmiller! - Warn when using data masking with "no-cache" operations. -
#12114
1d4ce00Thanks @jerelmiller! - Fix error when combining@unmaskand@deferdirectives on a fragment spread when data masking is enabled.
3.12.0-alpha.0
Minor Changes
-
#12042
1c0ecbfThanks @jerelmiller! - Introduces data masking into Apollo Client. Data masking allows components to access only the data they asked for through GraphQL fragments. This prevents coupling between components that might otherwise implicitly rely on fields not requested by the component. Data masking also provides the benefit that masked fields only rerender components that ask for the field.To enable data masking in Apollo Client, set the
dataMaskingoption totrue.new ApolloClient({ dataMasking: true, // ... other options });You can selectively disable data masking using the
@unmaskdirective. Apply this to any named fragment to receive all fields requested by the fragment.query { user { id ...UserFields @unmask } }To help with migration, use the
@unmaskmigrate mode which will add warnings when accessing fields that would otherwise be masked.query { user { id ...UserFields @unmask(mode: "migrate") } }
3.11.10
Patch Changes
- #12093
1765668Thanks @mgmolisani! - Fixed a bug when evaluating the devtools flag with the new syntaxdevtools.enabledthat could result totruewhen explicitly set tofalse.
3.11.9
Patch Changes
- #12110
a3f95c6Thanks @jerelmiller! - Fix an issue where errors returned from afetchMorecall from a Suspense hook would cause a Suspense boundary to be shown indefinitely.
3.11.8
Patch Changes
- #12054
35cf186Thanks @phryneas! - Fixed a bug where incorrect object access in some Safari extensions could cause a crash.
3.11.7
Patch Changes
- #12052
e471cefThanks @jerelmiller! - Fixes a regression from where passing an invalid identifier tofrominuseFragmentwould result in the warningTypeError: Cannot read properties of undefined (reading '__typename').
3.11.6
Patch Changes
-
#12049
9c26892Thanks @phryneas and @maciesielka! - Fix a bug whereuseFragmentdid not re-render as expected -
#12044
04462a2Thanks @DoctorJohn! - Cache theuseSubscriptionhook'srestartfunction definition between re-renders.
3.11.5
Patch Changes
-
#12027
eb3e21bThanks @JavaScriptBach! - TypeMutationResult.resetas an arrow function -
#12020
82d8cb4Thanks @jerelmiller! - Better conform to Rules of React by avoiding write of ref in render foruseFragment.
3.11.4
Patch Changes
-
#11994
41b17e5Thanks @jerelmiller! - Update theModifierfunction type to allowcache.modifyto return deeply partial data. -
#11989
e609156Thanks @phryneas! - Fix a potential crash when callingclearStorewhile a query was running.Previously, calling
client.clearStore()while a query was running had one of these results:useQuerywould stay in aloading: truestate.useLazyQuerywould stay in aloading: truestate, but also crash with a"Cannot read property 'data' of undefined"error.
Now, in both cases, the hook will enter an error state with a
networkError, and the promise returned by theuseLazyQueryexecutefunction will return a result in an error state. -
#11994
41b17e5Thanks @jerelmiller! - Prevent accidental distribution oncache.modifyfield modifiers when a field is a union type array.
3.11.3
Patch Changes
-
#11984
5db1659Thanks @jerelmiller! - Fix an issue where multiple fetches with results that returned errors would sometimes set thedataproperty with anerrorPolicyofnone. -
#11974
c95848eThanks @jerelmiller! - Fix an issue wherefetchMorewould write its result data to the cache when using it with ano-cachefetch policy. -
#11974
c95848eThanks @jerelmiller! - Fix an issue where executingfetchMorewith ano-cachefetch policy could sometimes result in multiple network requests. -
#11974
c95848eThanks @jerelmiller! -Potentially disruptive change
When calling
fetchMorewith a query that has ano-cachefetch policy,fetchMorewill now throw if anupdateQueryfunction is not provided. This provides a mechanism to merge the results from thefetchMorecall with the query's previous result.
3.11.2
Patch Changes
- #11980
38c0a2cThanks @jerelmiller! - Fix missinggetServerSnapshoterror when usinguseSubscriptionon the server.
3.11.1
Patch Changes
-
#11969
061cab6Thanks @jerelmiller! - Remove check forwindow.__APOLLO_CLIENT__when determining whether to connect to Apollo Client Devtools whenconnectToDevtoolsordevtools.enabledis not specified. This now simply checks to see if the application is in development mode. -
#11971
ecf77f6Thanks @jerelmiller! - Prevent thesetTimeoutfor suggesting devtools from running in non-browser environments.
3.11.0
Potentially Breaking Fixes
-
#11789
5793301Thanks @phryneas! - Changes usages of theGraphQLErrortype toGraphQLFormattedError.This was a type bug - these errors were never
GraphQLErrorinstances to begin with, and theGraphQLErrorclass has additional properties that can never be correctly rehydrated from a GraphQL result. The correct type to use here isGraphQLFormattedError.Similarly, please ensure to use the type
FormattedExecutionResultinstead ofExecutionResult- the non-"Formatted" versions of these types are for use on the server only, but don't get transported over the network. -
#11626
228429aThanks @phryneas! - CallnextFetchPolicywith "variables-changed" even if there is afetchPolicyspecified.Previously this would only be called when the current
fetchPolicywas equal to thefetchPolicyoption or the option was not specified. If you usenextFetchPolicyas a function, expect to see this function called more often.Due to this bug, this also meant that the
fetchPolicymight be reset to the initialfetchPolicy, even when you specified anextFetchPolicyfunction. If you previously relied on this behavior, you will need to update yournextFetchPolicycallback function to implement this resetting behavior.As an example, if your code looked like the following:
useQuery(QUERY, { nextFetchPolicy(currentFetchPolicy, info) { // your logic here } );Update your function to the following to reimplement the resetting behavior:
useQuery(QUERY, { nextFetchPolicy(currentFetchPolicy, info) { if (info.reason === 'variables-changed') { return info.initialFetchPolicy; } // your logic here } );
Minor Changes
-
#11923
d88c7f8Thanks @jerelmiller! - Add support forsubscribeToMorefunction touseQueryRefHandlers. -
#11854
3812800Thanks @jcostello-atlassian! - Support extensions in useSubscription -
#11923
d88c7f8Thanks @jerelmiller! - Add support forsubscribeToMorefunction touseLoadableQuery. -
#11863
98e44f7Thanks @phryneas! - ReimplementuseSubscriptionto fix rules of React violations. -
#11869
a69327cThanks @phryneas! - Rewrite big parts ofuseQueryanduseLazyQueryto be more compliant with the Rules of React and React Compiler -
#11936
1b23337Thanks @jerelmiller! - Add the ability to specify a name for the client instance for use with Apollo Client Devtools. This is useful when instantiating multiple clients to identify the client instance more easily. This deprecates theconnectToDevtoolsoption in favor of a newdevtoolsconfiguration.new ApolloClient({ devtools: { enabled: true, name: "Test Client", }, });This option is backwards-compatible with
connectToDevtoolsand will be used in the absense of adevtoolsoption. -
#11923
d88c7f8Thanks @jerelmiller! - Add support forsubscribeToMorefunction touseBackgroundQuery. -
#11930
a768575Thanks @jerelmiller! - Deprecates experimental schema testing utilities introduced in 3.10 in favor of recommending@apollo/graphql-testing-library.
Patch Changes
-
#11951
0de03afThanks @phryneas! - add React 19 RC topeerDependencies -
#11927
2941824Thanks @phryneas! - Addrestartfunction touseSubscription. -
#11949
4528918Thanks @alessbell! - Remove deprecatedwatchFragmentoption,canonizeResults -
#11937
78332beThanks @phryneas! -createSchemaFetch: simulate serialized errors instead of anApolloErrorinstance -
#11902
96422ceThanks @phryneas! - Addcausefield toApolloError. -
#11806
8df6013Thanks @phryneas! - MockLink: add query default variables if not specified in mock request -
#11926
3dd6432Thanks @phryneas! -watchFragment: forward additional options todiffOptions -
#11946
7d833b8Thanks @jerelmiller! - Fix issue where mutations were not accessible by Apollo Client Devtools in 3.11.0-rc.0. -
#11944
8f3d7ebThanks @sneyderdev! - AllowIgnoreModifierto be returned from aoptimisticResponsefunction when inferring from aTypedDocumentNodewhen used with a generic argument. -
#11954
4a6e86aThanks @phryneas! - Document (and deprecate) the previously undocumentederrorsproperty on theuseQueryQueryResulttype. -
#11719
09a6677Thanks @phryneas! - Allow wrappingcreateQueryPreloader -
#11921
70406bfThanks @phryneas! - addignoreResultsoption touseSubscription
3.11.0-rc.2
Patch Changes
-
#11951
0de03afThanks @phryneas! - add React 19 RC topeerDependencies -
#11937
78332beThanks @phryneas! -createSchemaFetch: simulate serialized errors instead of anApolloErrorinstance -
#11944
8f3d7ebThanks @sneyderdev! - AllowIgnoreModifierto be returned from aoptimisticResponsefunction when inferring from aTypedDocumentNodewhen used with a generic argument. -
#11954
4a6e86aThanks @phryneas! - Document (and deprecate) the previously undocumentederrorsproperty on theuseQueryQueryResulttype.
3.11.0-rc.1
Patch Changes
-
#11949
4528918Thanks @alessbell! - Remove deprecatedwatchFragmentoption,canonizeResults -
#11926
3dd6432Thanks @phryneas! -watchFragment: forward additional options todiffOptions -
#11946
7d833b8Thanks @jerelmiller! - Fix issue where mutations were not accessible by Apollo Client Devtools in 3.11.0-rc.0.
3.11.0-rc.0
Minor Changes
-
#11923
d88c7f8Thanks @jerelmiller! - Add support forsubscribeToMorefunction touseQueryRefHandlers. -
#11854
3812800Thanks @jcostello-atlassian! - Support extensions in useSubscription -
#11923
d88c7f8Thanks @jerelmiller! - Add support forsubscribeToMorefunction touseLoadableQuery. -
#11863
98e44f7Thanks @phryneas! - ReimplementuseSubscriptionto fix rules of React violations. -
#11869
a69327cThanks @phryneas! - Rewrite big parts ofuseQueryanduseLazyQueryto be more compliant with the Rules of React and React Compiler -
#11936
1b23337Thanks @jerelmiller! - Add the ability to specify a name for the client instance for use with Apollo Client Devtools. This is useful when instantiating multiple clients to identify the client instance more easily. This deprecates theconnectToDevtoolsoption in favor of a newdevtoolsconfiguration.new ApolloClient({ devtools: { enabled: true, name: "Test Client", }, });This option is backwards-compatible with
connectToDevtoolsand will be used in the absense of adevtoolsoption. -
#11923
d88c7f8Thanks @jerelmiller! - Add support forsubscribeToMorefunction touseBackgroundQuery. -
#11789
5793301Thanks @phryneas! - Changes usages of theGraphQLErrortype toGraphQLFormattedError.This was a type bug - these errors were never
GraphQLErrorinstances to begin with, and theGraphQLErrorclass has additional properties that can never be correctly rehydrated from a GraphQL result. The correct type to use here isGraphQLFormattedError.Similarly, please ensure to use the type
FormattedExecutionResultinstead ofExecutionResult- the non-"Formatted" versions of these types are for use on the server only, but don't get transported over the network. -
#11930
a768575Thanks @jerelmiller! - Deprecates experimental schema testing utilities introduced in 3.10 in favor of recommending@apollo/graphql-testing-library.
Patch Changes
-
#11927
2941824Thanks @phryneas! - Addrestartfunction touseSubscription. -
#11902
96422ceThanks @phryneas! - Addcausefield toApolloError. -
#11806
8df6013Thanks @phryneas! - MockLink: add query default variables if not specified in mock request -
#11626
228429aThanks @phryneas! - CallnextFetchPolicywith "variables-changed" even if there is afetchPolicyspecified. (fixes #11365) -
#11719
09a6677Thanks @phryneas! - Allow wrappingcreateQueryPreloader -
#11921
70406bfThanks @phryneas! - addignoreResultsoption touseSubscription
3.10.8
Patch Changes
- #11911
1f0460aThanks @jerelmiller! - Allowundefinedto be returned from acache.modifymodifier function when a generic type argument is used.
3.10.7
Patch Changes
-
#11901
10a8c0aThanks @phryneas! - updatecanUseLayoutEffectcheck to also allow for layout effects in React Native -
#11861
1aed0e8Thanks @henryqdineen! - Defend against non-serializable params ininvariantWrappers -
#11905
29755daThanks @phryneas! - Add.d.ctsfiles for cjs bundles -
#11906
d104759Thanks @phryneas! - chore: update TypeScript to 5.5
3.10.6
Patch Changes
- #11900
f745558Thanks @phryneas! -useMutation: useuseIsomorphicLayoutEffectinstead ofuseLayoutEffect
3.10.5
Patch Changes
-
#11888
7fb7939Thanks @phryneas! - switchuseRenderGuardto an approach not accessing React's internals -
#11511
6536369Thanks @phryneas! -useLoadableQuery: ensure thatloadQueryis updated if the ApolloClient instance changes -
#11860
8740f19Thanks @alessbell! - Fixes #11849 by reevaluatingwindow.fetcheach timeBatchHttpLinkuses it, if not configured viaoptions.fetch. Takes the same approach as PR #8603 which fixed the same issue inHttpLink. -
#11852
d502a69Thanks @phryneas! - Fix a bug where calling theuseMutationresetfunction would point the hook to an outdatedclientreference. -
#11329
3d164eaThanks @PaLy! - Fix graphQLErrors in Error Link if networkError.result is an empty string -
#11852
d502a69Thanks @phryneas! - Prevent writing to a ref in render inuseMutation. As a result, you might encounter problems in the future if you call the mutation'sexecutefunction during render. Please note that this was never supported behavior, and we strongly recommend against it. -
#11848
ad63924Thanks @phryneas! - Ensure covariant behavior:MockedResponse<X,Y>should be assignable toMockedResponse -
#11851
45c47beThanks @phryneas! - Avoid usage of useRef in useInternalState to prevent ref access in render. -
#11877
634d91aThanks @phryneas! - Add missing name to tuple member (fix TS5084) -
#11851
45c47beThanks @phryneas! - Fix a bug whereuseLazyQuerywould not pick up a client change.
3.10.4
Patch Changes
-
#11838
8475346Thanks @alex-kinokon! - Don’t prompt for DevTools installation for browser extension page -
#11839
6481fe1Thanks @jerelmiller! - Fix a regression in 3.9.5 where a merge function that returned an incomplete result would not allow the client to refetch in order to fulfill the query. -
#11844
86984f2Thanks @jerelmiller! - Honor the@nonreactivedirective when usingcache.watchFragmentor theuseFragmenthook to avoid rerendering when using these directives. -
#11824
47ad806Thanks @phryneas! - Create brandedQueryReftype without exposed properties.This change deprecates
QueryReferencein favor of aQueryReftype that doesn't expose any properties. This change also updatespreloadQueryto return a newPreloadedQueryReftype, which exposes thetoPromisefunction as it does today. This means that query refs produced byuseBackgroundQueryanduseLoadableQuerynow returnQueryReftypes that do not have access to atoPromisefunction, which was never meant to be used in combination with these hooks.While we tend to avoid any types of breaking changes in patch releases as this, this change was necessary to support an upcoming version of the React Server Component integration, which needed to omit the
toPromisefunction that would otherwise have broken at runtime. Note that this is a TypeScript-only change. At runtime,toPromiseis still present on all queryRefs currently created by this package - but we strongly want to discourage you from accessing it in all cases except for thePreloadedQueryRefuse case.Migration is as simple as replacing all references to
QueryReferencewithQueryRef, so it should be possible to do this with a search & replace in most code bases:-import { QueryReference } from '@apollo/client' +import { QueryRef } from '@apollo/client' - function Component({ queryRef }: { queryRef: QueryReference<TData> }) { + function Component({ queryRef }: { queryRef: QueryRef<TData> }) { // ... } -
#11845
4c5c820Thanks @jerelmiller! - Remove@nonreactivedirectives from queries passed toMockLinkto ensure they are properly matched. -
#11837
dff15b1Thanks @jerelmiller! - Fix an issue where a polled query created in React strict mode may not stop polling after the component unmounts while using thecache-and-networkfetch policy.
3.10.3
Patch Changes
-
#11811
d67d7f9Thanks @phryneas! - Adjust some types for React 19 compat -
#11834
7d8aad4Thanks @psamim! - Fix error "Cannot convert object to primitive value"
3.10.2
Patch Changes
-
#11821
2675d3cThanks @jerelmiller! - Fix a regression where rerendering a component withuseBackgroundQuerywould recreate thequeryRefinstance when used with React's strict mode. -
#11821
2675d3cThanks @jerelmiller! - Revert the change introduced in 3.9.10 via #11738 that disposed of queryRefs synchronously. This change caused too many issues with strict mode.
3.10.1
Patch Changes
-
#11792
5876c35Thanks @phryneas! - AutoCleanedCache: only schedule batched cache cleanup if the cache is full (fixes #11790) -
#11799
1aca7edThanks @phryneas! -RenderPromises: usecanonicalStringifyto serializevariablesto ensure query deduplication is properly applied even whenvariablesare specified in a different order. -
#11803
bf9dd17Thanks @phryneas! - Update therehacktdependency to^0.1.0 -
#11756
60592e9Thanks @henryqdineen! - Fix operation.setContext() type
3.10.0
Minor Changes
-
#11605
e2dd4c9Thanks @alessbell! - AddscreateMockFetchutility for integration testing that includes the link chain -
#11760
acd1982Thanks @alessbell! -createTestSchemanow uses graphql-toolsmergeResolversto merge resolvers instead of a shallow merge. -
#11764
f046aa9Thanks @alessbell! - RenamecreateProxiedSchematocreateTestSchemaandcreateMockFetchtocreateSchemaFetch. -
#11777
5dfc79fThanks @alessbell! - CallcreateMockSchemainsidecreateTestSchema. -
#11774
2583488Thanks @alessbell! - Add ability to set min and max delay increateSchemaFetch -
#11605
e2dd4c9Thanks @alessbell! - Adds proxiedSchema and createMockSchema testing utilities -
#11465
7623da7Thanks @alessbell! - AddwatchFragmentmethod to the cache and expose it on ApolloClient, refactoruseFragmentusingwatchFragment. -
#11743
78891f9Thanks @jerelmiller! - Remove alpha designation forqueryRef.toPromise()to stabilize the API. -
#11743
78891f9Thanks @jerelmiller! - Remove alpha designation forcreateQueryPreloaderto stabilize the API. -
#11783
440563aThanks @alessbell! - Moves new testing utilities to their own entrypoint,testing/experimental
Patch Changes
-
#11757
9825295Thanks @phryneas! - AdjustuseReadQuerywrapper logic to work with transported objects. -
#11771
e72cbbaThanks @phryneas! - WrapuseQueryRefHandlersinwrapHook. -
#11754
80d2ba5Thanks @alessbell! - ExportWatchFragmentOptionsandWatchFragmentResultfrom main entrypoint and fix bug wherethiswasn't bound to thewatchFragmentmethod onApolloClient.
3.10.0-rc.1
Minor Changes
-
#11760
acd1982Thanks @alessbell! -createTestSchemanow uses graphql-toolsmergeResolversto merge resolvers instead of a shallow merge. -
#11764
f046aa9Thanks @alessbell! - RenamecreateProxiedSchematocreateTestSchemaandcreateMockFetchtocreateSchemaFetch. -
#11777
5dfc79fThanks @alessbell! - CallcreateMockSchemainsidecreateTestSchema. -
#11774
2583488Thanks @alessbell! - Add ability to set min and max delay increateSchemaFetch -
#11783
440563aThanks @alessbell! - Moves new testing utilities to their own entrypoint,testing/experimental
Patch Changes
-
#11757
9825295Thanks @phryneas! - AdjustuseReadQuerywrapper logic to work with transported objects. -
#11771
e72cbbaThanks @phryneas! - WrapuseQueryRefHandlersinwrapHook. -
#11754
80d2ba5Thanks @alessbell! - ExportWatchFragmentOptionsandWatchFragmentResultfrom main entrypoint and fix bug wherethiswasn't bound to thewatchFragmentmethod onApolloClient.
3.10.0-rc.0
Minor Changes
-
#11605
e2dd4c9Thanks @alessbell! - AddscreateMockFetchutility for integration testing that includes the link chain -
#11605
e2dd4c9Thanks @alessbell! - Adds proxiedSchema and createMockSchema testing utilities -
#11743
78891f9Thanks @jerelmiller! - Remove alpha designation forqueryRef.toPromise()to stabilize the API. -
#11743
78891f9Thanks @jerelmiller! - Remove alpha designation forcreateQueryPreloaderto stabilize the API.
3.10.0-alpha.0
Minor Changes
- #11465
7623da7Thanks @alessbell! - AddwatchFragmentmethod to the cache and expose it on ApolloClient, refactoruseFragmentusingwatchFragment.
3.9.11
Patch Changes
- #11769
04132afThanks @jerelmiller! - Fix an issue where usingskipTokenor theskipoption withuseSuspenseQueryin React's strict mode would perform a network request.
3.9.10
Patch Changes
-
#11738
b1a5eb8Thanks @jerelmiller! - Fix an issue where rerenderinguseBackgroundQueryafter thequeryRefhad been disposed, either via the auto dispose timeout or by unmountinguseReadQuery, would cause thequeryRefto be recreated potentially resulting in another network request. -
#11738
b1a5eb8Thanks @jerelmiller! - Allow queryRefs to be disposed of synchronously when a suspense hook unmounts. This prevents some situations where using a suspense hook with the same query/variables as the disposed queryRef accidentally used the disposed queryRef rather than creating a new instance. -
#11670
cc5c03bThanks @phryneas! - Bail out ofexecuteSubSelectedArraycalls if the array has 0 elements.
3.9.9
Patch Changes
- #11696
466ef82Thanks @PiR1! - Immediately dispose of thequeryRefifuseBackgroundQueryunmounts before the auto dispose timeout kicks in.
3.9.8
Patch Changes
-
#11706
8619bc7Thanks @jerelmiller! - Fix issue in all suspense hooks where returning an empty array after callingfetchMorewould rerender the component with an empty list. -
#11694
835d5f3Thanks @phryneas! - ExposesetErrorMessageHandlerfrom@apollo/client/deventrypoint. -
#11689
cb8ffe5Thanks @jerelmiller! - Fix issue where passing a newfromoption touseFragmentwould first render with the previous value before rerendering with the correct value. -
#11713
642092cThanks @jerelmiller! - Fix issue where setting a defaultwatchQueryoption in theApolloClientconstructor could breakstartTransitionwhen used with suspense hooks.
3.9.7
Patch Changes
-
#11659
652a61eThanks @phryneas! - MakeuseRenderGuardmore resilient to changes in React internals. -
#11594
50b1097Thanks @alessbell! - Adds a fix for multipart subscriptions that terminate with payload: null
3.9.6
Patch Changes
-
#11617
f1d8bc4Thanks @phryneas! - Allow Apollo Client instance to intercept hook functionality -
#11638
bf93adaThanks @jerelmiller! - Fix issue where callingfetchMorefrom a suspense-enabled hook insidestartTransitioncaused an unnecessary rerender.
3.9.5
Patch Changes
-
#11595
8c20955Thanks @phryneas! - Bumps the dependencyrehacktto 0.0.5 -
#11592
1133469Thanks @Stephen2! - StrengthenMockedResponse.newDatatype -
#11579
1ba2fd9Thanks @jerelmiller! - Fix issue where partial data is reported touseQuerywhen usingnotifyOnNetworkStatusChangeafter it errors while another overlapping query succeeds. -
#11579
1ba2fd9Thanks @jerelmiller! - Fix an issue where a partial cache write for an errored query would result in automatically refetching that query. -
#11562
65ab695Thanks @mspiess! - Mocks with an infinite delay no longer require result or error
3.9.4
Patch Changes
-
#11403
b0c4f3aThanks @jerelmiller! - Fix issue inuseLazyQuerythat results in a double network call when calling the execute function with no arguments after having called it previously with another set of arguments. -
#11576
e855d00Thanks @alessbell! - Revert PR #11202 to fix caching bug reported in #11560
3.9.3
Patch Changes
-
#11525
dce923aThanks @vezaynk! - Allows passing in client via options to useFragment -
#11558
8cba16fThanks @alessbell! - Fixunbound-methodlinter error on ObservableQuery methods exposed on useQuery's QueryResult object.
3.9.2
Patch Changes
- #11552
6ac2b0cThanks @jerelmiller! - Fix import inuseLazyRefcausing import issues in the nextjs package.
3.9.1
Patch Changes
-
#11516
8390feaThanks @phryneas! - Fix an incorrect string substitution in a warning message. -
#11515
c9bf93bThanks @vladar! - Avoid redundant refetchQueries call for mutation with no-cache policy (fixes #10238) -
#11545
84a6beaThanks @alessbell! - Remove error thrown byinFlightLinkObservablesintended to be removed before 3.9 release.
3.9.0
Minor Changes
Memory optimizations
-
#11424
62f3b6dThanks @phryneas! - Simplify RetryLink, fix potential memory leakHistorically,
RetryLinkwould keep avaluesarray of all previous values, in case the operation would get an additional subscriber at a later point in time.In practice, this could lead to a memory leak (#11393) and did not serve any further purpose, as the resulting observable would only be subscribed to by Apollo Client itself, and only once - it would be wrapped in a
Concastbefore being exposed to the user, and thatConcastwould handle subscribers on its own. -
#11435
5cce53eThanks @phryneas! - DeprecatescanonizeResults.Using
canonizeResultscan result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks. -
#11254
d08970dThanks @benjamn! - DecouplecanonicalStringifyfromObjectCanonfor better time and memory performance. -
#11356
cc4ac7eThanks @phryneas! - Fix a potential memory leak inFragmentRegistry.transformandFragmentRegistry.findFragmentSpreadsthat would hold on to passed-inDocumentNodesfor too long. -
#11370
25e2cb4Thanks @phryneas! -parsefunction: improve memory management- use LRU
WeakCacheinstead ofMapto keep a limited number of parsed results - cache is initiated lazily, only when needed
- expose
parse.resetCache()method
- use LRU
-
#11389
139acd1Thanks @phryneas! -documentTransform: useoptimismandWeakCacheinstead of directly storing data on theTrie -
#11358
7d939f8Thanks @phryneas! - Fixes a potential memory leak inConcastthat might have been triggered whenConcastwas used outside of Apollo Client. -
#11344
bd26676Thanks @phryneas! - Add aresetCachemethod toDocumentTransformand hookInMemoryCache.addTypenameTransformup toInMemoryCache.gc -
#11367
30d17bfThanks @phryneas! -print: useWeakCacheinstead ofWeakMap -
#11387
4dce867Thanks @phryneas! -QueryManager.transformCache: useWeakCacheinstead ofWeakMap -
#11369
2a47164Thanks @phryneas! - Persisted Query Link: improve memory management- use LRU
WeakCacheinstead ofWeakMapto keep a limited number of hash results - hash cache is initiated lazily, only when needed
- expose
persistedLink.resetHashCache()method - reset hash cache if the upstream server reports it doesn't accept persisted queries
- use LRU
-
#10804
221dd99Thanks @phryneas! - use WeakMap in React Native with Hermes -
#11355
7d8e184Thanks @phryneas! - InMemoryCache.gc now also triggers FragmentRegistry.resetCaches (if there is a FragmentRegistry) -
#11409
2e7203bThanks @phryneas! - Adds an experimentalApolloClient.getMemoryInternalshelper -
#11343
776631dThanks @phryneas! - Addresetmethod toprint, hook up toInMemoryCache.gc
Suspense-enabled data fetching on user interaction with useLoadableQuery
-
#11300
a815873Thanks @jerelmiller! - Introduces a newuseLoadableQueryhook. This hook works similarly touseBackgroundQueryin that it returns aqueryRefthat can be used to suspend a component via theuseReadQueryhook. It provides a more ergonomic way to load the query during a user interaction (for example when wanting to preload some data) that would otherwise be clunky withuseBackgroundQuery.function App() { const [loadQuery, queryRef, { refetch, fetchMore, reset }] = useLoadableQuery(query, options); return ( <> <button onClick={() => loadQuery(variables)}>Load query</button> <Suspense fallback={<SuspenseFallback />}> {queryRef && <Child queryRef={queryRef} />} </Suspense> </> ); } function Child({ queryRef }) { const { data } = useReadQuery(queryRef); // ... }
Begin preloading outside of React with createQueryPreloader
-
#11412
58db5c3Thanks @jerelmiller! - Add the ability to start preloading a query outside React to begin fetching as early as possible. CallcreateQueryPreloaderto create apreloadQueryfunction which can be called to start fetching a query. This returns aqueryRefwhich is passed touseReadQueryand suspended until the query is done fetching.const preloadQuery = createQueryPreloader(client); const queryRef = preloadQuery(QUERY, { variables, ...otherOptions }); function App() { return { <Suspense fallback={<div>Loading</div>}> <MyQuery /> </Suspense> } } function MyQuery() { const { data } = useReadQuery(queryRef); // do something with data }
Testing utility improvements
-
#11178
4d64a6fThanks @sebakerckhof! - Support re-using of mocks in the MockedProvider -
#6701
8d2b4e1Thanks @prowe! - Ability to dynamically match mocksAdds support for a new property
MockedResponse.variableMatcher: a predicate function that accepts avariablesparam. Iftrue, thevariableswill be passed into theResultFunctionto help dynamically build a response.
New useQueryRefHandlers hook
-
#11412
58db5c3Thanks @jerelmiller! - Create a newuseQueryRefHandlershook that returnsrefetchandfetchMorefunctions for a givenqueryRef. This is useful to get access to handlers for aqueryRefthat was created bycreateQueryPreloaderor when the handlers for aqueryRefproduced by a different component are inaccessible.const MyComponent({ queryRef }) { const { refetch, fetchMore } = useQueryRefHandlers(queryRef); // ... }
Bail out of optimisticResponse updates with the IGNORE sentinel object
-
#11410
07fcf6aThanks @sf-twingate! - Allow returningIGNOREsentinel object fromoptimisticResponsefunctions to bail-out from the optimistic update.Consider this example:
const UPDATE_COMMENT = gql` mutation UpdateComment($commentId: ID!, $commentContent: String!) { updateComment(commentId: $commentId, content: $commentContent) { id __typename content } } `; function CommentPageWithData() { const [mutate] = useMutation(UPDATE_COMMENT); return ( <Comment updateComment={({ commentId, commentContent }) => mutate({ variables: { commentId, commentContent }, optimisticResponse: (vars, { IGNORE }) => { if (commentContent === "foo") { // conditionally bail out of optimistic updates return IGNORE; } return { updateComment: { id: commentId, __typename: "Comment", content: commentContent, }, }; }, }) } /> ); }The
IGNOREsentinel can be destructured from the second parameter in the callback function signature passed tooptimisticResponse.
Network adapters for multipart subscriptions usage with Relay and urql
-
#11301
46ab032Thanks @alessbell! - Add multipart subscription network adapters for Relay and urqlRelay
import { createFetchMultipartSubscription } from "@apollo/client/utilities/subscriptions/relay"; import { Environment, Network, RecordSource, Store } from "relay-runtime"; const fetchMultipartSubs = createFetchMultipartSubscription( "http://localhost:4000" ); const network = Network.create(fetchQuery, fetchMultipartSubs); export const RelayEnvironment = new Environment({ network, store: new Store(new RecordSource()), });Urql
import { createFetchMultipartSubscription } from "@apollo/client/utilities/subscriptions/urql"; import { Client, fetchExchange, subscriptionExchange } from "@urql/core"; const url = "http://localhost:4000"; const multipartSubscriptionForwarder = createFetchMultipartSubscription(url); const client = new Client({ url, exchanges: [ fetchExchange, subscriptionExchange({ forwardSubscription: multipartSubscriptionForwarder, }), ], });
skipPollAttempt callback function
-
#11397
3f7eecbThanks @aditya-kumawat! - Adds a newskipPollAttemptcallback function that's called whenever a refetch attempt occurs while polling. If the function returnstrue, the refetch is skipped and not reattempted until the next poll interval. This will solve the frequent use-case of disabling polling when the window is inactive.useQuery(QUERY, { pollInterval: 1000, skipPollAttempt: () => document.hidden, // or !document.hasFocus() }); // or define it globally new ApolloClient({ defaultOptions: { watchQuery: { skipPollAttempt: () => document.hidden, // or !document.hasFocus() }, }, });
QueryManager.inFlightLinkObservables now uses a strong Trie as an internal data structure
-
#11345
1759066Thanks @phryneas!Warning: requires
@apollo/experimental-nextjs-app-supportupdateIf you are using
@apollo/experimental-nextjs-app-support, you will need to update that to at least 0.5.2, as it accesses this internal data structure.
More Minor Changes
-
#11202
7c2bc08Thanks @benjamn! - PreventQueryInfo#markResultmutation ofresult.dataand return cache data consistently whether complete or incomplete. -
#11442
4b6f2bcThanks @jerelmiller! - Remove the need to callretainfromuseLoadableQuerysinceuseReadQuerywill now retain the query. This means that aqueryRefthat is not consumed byuseReadQuerywithin the givenautoDisposeTimeoutMswill now be auto diposed for you.Thanks to #11412, disposed query refs will be automatically resubscribed to the query when consumed by
useReadQueryafter it has been disposed. -
#11438
6d46ab9Thanks @jerelmiller! - Remove the need to callretainfromuseBackgroundQuerysinceuseReadQuerywill now retain the query. This means that aqueryRefthat is not consumed byuseReadQuerywithin the givenautoDisposeTimeoutMswill now be auto diposed for you.Thanks to #11412, disposed query refs will be automatically resubscribed to the query when consumed by
useReadQueryafter it has been disposed. -
#11175
d6d1491Thanks @phryneas! - To work around issues in React Server Components, especially with bundling for the Next.js "edge" runtime we now use an external package to wrapreactimports instead of importing React directly. -
#11495
1190aa5Thanks @jerelmiller! - Increase the default memory limits forexecuteSelectionSetandexecuteSelectionSetArray.
Patch Changes
-
#11275
3862f9bThanks @phryneas! - Add adefaultContextoption and property onApolloClient, e.g. for keeping track of changing auth tokens or dependency injection.This can be used e.g. in authentication scenarios, where a new token might be generated outside of the link chain and should passed into the link chain.
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client"; import { setContext } from "@apollo/client/link/context"; const httpLink = createHttpLink({ uri: "/graphql", }); const authLink = setContext((_, { headers, token }) => { return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "", }, }; }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(), }); // somewhere else in your application function onNewToken(newToken) { // token can now be changed for future requests without need for a global // variable, scoped ref or recreating the client client.defaultContext.token = newToken; } -
#11443
ff5a332Thanks @phryneas! - Adds a deprecation warning to the HOC and render prop APIs.The HOC and render prop APIs have already been deprecated since 2020, but we previously didn't have a
@deprecatedtag in the DocBlocks. -
#11385
d9ca4f0Thanks @phryneas! - ensuredefaultContextis also used for mutations and subscriptions -
#11503
67f62e3Thanks @jerelmiller! - Release changes fromv3.8.10 -
#11078
14edebeThanks @phryneas! - ObservableQuery: prevent reporting results of previous queries if the variables changed since -
#11439
33454f0Thanks @jerelmiller! - Address bundling issue introduced in #11412 where thereact/cacheinternals ended up duplicated in the bundle. This was due to the fact that we had areact/hooksentrypoint that imported these files along with the newly introducedcreateQueryPreloaderfunction, which lived outside of thereact/hooksfolder. -
#11371
ebd8fe2Thanks @phryneas! - Clarify types ofEntityStore.makeCacheKey.
3.8.10
Patch Changes
-
#11489
abfd02aThanks @gronxb! - FixnetworkStatuswithuseSuspenseQuerynot properly updating to ready state when using acache-and-networkfetch policy that returns data equal to what is already in the cache. -
#11483
6394ddaThanks @pipopotamasu! - Fix cache override warning output
3.8.9
Patch Changes
-
#11472
afc844dThanks @alessbell! - Fix delay: Infinity when set on a MockResponse passed to Mocked Provider so it indefinitely enters loading state. -
#11464
aac12b2Thanks @jerelmiller! - PreventuseFragmentfrom excessively unsubscribing and resubscribing the fragment with the cache on every render. -
#11449
f40cda4Thanks @phryneas! - Removes refences to the typescript "dom" lib. -
#11470
e293bc9Thanks @phryneas! - Remove an unnecessary check from parseAndCheckHttpResponse.
3.8.8
Patch Changes
-
#11200
ae5091a21Thanks @jerelmiller! - Enablestrictin tsconfig for the entire project. -
#11332
291aea56bThanks @asvishnyakov! - Add missed reexports of MutationFetchPolicy and RefetchWritePolicy to @apollo/client/core -
#10931
e5acf910eThanks @phryneas! -useMutation: also reset internal state on reset
3.8.7
Patch Changes
-
#11297
c8c76a522Thanks @jerelmiller! - Add an explicit return type for theuseReadQueryhook calledUseReadQueryResult. Previously the return type of this hook was inferred from the return value. -
#11337
bb1da8349Thanks @phryneas! - #11206 used the TypeScript syntaxinfer X extends Ythat was introduced in TS 4.8. This caused some problems for some users, so we are rolling back to a more backwars-compatible (albeit slightly less performant) type.
3.8.6
Patch Changes
-
#11291
2be7eafe3Thanks @ArioA! - Fix a bug that allows to only callloadErrorMessageswithout also callingloadDevErrorMessages. -
#11274
b29f000f3Thanks @jerelmiller! - Start the query ref auto dispose timeout after the initial promise has settled. This prevents requests that run longer than the timeout duration from keeping the component suspended indefinitely. -
#11289
b5894dbf0Thanks @phryneas! -MockedProvider: defaultconnectToDevToolstofalsein createdApolloClientinstance.This will prevent the mocked
ApolloClientinstance from trying to connect to the DevTools, which would start asetTimeoutthat might keep running after a test has finished. -
#11206
dd2ce7687Thanks @phryneas! -cache.modify: Less strict types & new dev runtime warnings.
3.8.5
Patch Changes
-
#11266
5192cf6e1Thanks @phryneas! - Fixes argument handling for invariant log messages. -
#11235
6cddaaf65Thanks @phryneas! - Fix nextFetchPolicy behaviour with transformed documents by keepingoptionsreference stable when passing it through QueryManager. -
#11252
327a2abbdThanks @phryneas! - Fixes a race condition in asyncMap that caused issues in React Native when errors were returned in the response payload along with a data property that was null. -
#11229
c372bad4eThanks @phryneas! - Remove (already throwing) SuspenseCache export that should have been removed in 3.8.
3.8.4
Patch Changes
- #11195
9e59b251dThanks @phryneas! - Forinvariant.logetc., error arguments are now serialized correctly in the link to the error page.
3.8.3
Patch Changes
3.8.2
Patch Changes
-
#10072
51045c336Thanks @Huulivoide! - Fixes race conditions in useReactiveVar that may prevent updates to the reactive variable from propagating through the hook. -
#11162
d9685f53cThanks @jerelmiller! - Ensures GraphQL errors returned in subscription payloads adhere to theerrorPolicyset inclient.subscribe(...)calls. -
#11134
96492e142Thanks @alessbell! - Use separate type imports in useSuspenseQuery and useBackgroundQuery to workaround SWC compiler issue. -
#11117
6b8198109Thanks @phryneas! - Adds a new devtools registration mechanism and tweaks the mechanism behind the "devtools not found" mechanic. -
#11186
f1d429f32Thanks @jerelmiller! - Fix an issue where race conditions when rapidly switching between variables would sometimes result in the wrongdatareturned from the query. Specifically this occurs when a query is triggered with an initial set of variables (VariablesA), then triggers the same query with another set of variables (VariablesB) but switches back to theVariablesAbefore the response forVariablesBis returned. Previously this would result in the data forVariablesBto be displayed whileVariablesAwas active. The data is forVariablesAis now properly returned. -
#11163
a8a9e11e9Thanks @bignimbus! - Fix typo in error message: "occured" -> "occurred" -
#11180
7d9c481e5Thanks @jerelmiller! - Fixes an issue where refetching fromuseBackgroundQueryviarefetchwith an error after an error was already fetched would get stuck in a loading state.
3.8.1
Patch Changes
-
#11141
c469b1616Thanks @jerelmiller! - Remove newly exported response iterator helpers that caused problems on some installs where@types/nodewas not available.IMPORTANT
The following exports were added in version 3.8.0 that are removed with this patch.
isAsyncIterableIteratorisBlobisNodeReadableStreamisNodeResponseisReadableStreamisStreamableBlob
3.8.0
Minor Changes
Fetching with Suspense 🎉
-
#10323
64cb88a4bThanks @jerelmiller! - Add support for React suspense with a newuseSuspenseQueryhook.useSuspenseQueryinitiates a network request and causes the component calling it to suspend while the request is in flight. It can be thought of as a drop-in replacement foruseQuerythat allows you to take advantage of React's concurrent features while fetching during render.Consider a
Dogcomponent that fetches and renders some information about a dog named Mozzarella:View code 🐶
import { Suspense } from "react"; import { gql, TypedDocumentNode, useSuspenseQuery } from "@apollo/client"; interface Data { dog: { id: string; name: string; }; } interface Variables { name: string; } const GET_DOG_QUERY: TypedDocumentNode<Data, Variables> = gql` query GetDog($name: String) { dog(name: $name) { id name } } `; function App() { return ( <Suspense fallback={<div>Loading...</div>}> <Dog name="Mozzarella" /> </Suspense> ); } function Dog({ name }: { name: string }) { const { data } = useSuspenseQuery(GET_DOG_QUERY, { variables: { name }, }); return <>Name: {data.dog.name}</>; }For a detailed explanation of
useSuspenseQuery, see our fetching with Suspense reference. -
#10755
e3c676debThanks @alessbell! - Feature: addsuseBackgroundQueryanduseReadQueryhooksuseBackgroundQueryinitiates a request for data in a parent component and returns aQueryReferencewhich is used to read the data in a child component viauseReadQuery. If the child component attempts to render before the data can be found in the cache, the child component will suspend until the data is available. On cache updates to watched data, the child component callinguseReadQuerywill re-render with new data but the parent component will not re-render (as it would, for example, if it were usinguseQueryto issue the request).Consider an
Appcomponent that fetches a list of breeds in the background while also fetching and rendering some information about an individual dog, Mozzarella:View code 🐶
function App() { const [queryRef] = useBackgroundQuery(GET_BREEDS_QUERY); return ( <Suspense fallback={<div>Loading...</div>}> <Dog name="Mozzarella" queryRef={queryRef} /> </Suspense> ); } function Dog({ name, queryRef, }: { name: string; queryRef: QueryReference<BreedData>; }) { const { data } = useSuspenseQuery(GET_DOG_QUERY, { variables: { name }, }); return ( <> Name: {data.dog.name} <Suspense fallback={<div>Loading breeds...</div>}> <Breeds queryRef={queryRef} /> </Suspense> </> ); } function Breeds({ queryRef }: { queryRef: QueryReference<BreedData> }) { const { data } = useReadQuery(queryRef); return data.breeds.map(({ characteristics }) => characteristics.map((characteristic) => ( <div key={characteristic}>{characteristic}</div> )) ); }For a detailed explanation of
useBackgroundQueryanduseReadQuery, see our fetching with Suspense reference.
Document transforms 📑
-
#10509
79df2c7baThanks @jerelmiller! - Add the ability to specify custom GraphQL document transforms. These transforms are run before reading data from the cache, before local state is resolved, and before the query document is sent through the link chain.To register a custom document transform, create a transform using the
DocumentTransformclass and pass it to thedocumentTransformoption onApolloClient.import { DocumentTransform } from "@apollo/client"; const documentTransform = new DocumentTransform((document) => { // do something with `document` return transformedDocument; }); const client = new ApolloClient({ documentTransform: documentTransform });For more information on the behavior and API of
DocumentTransform, see its reference page in our documentation.
New removeTypenameFromVariables link 🔗
-
#10853
300957960Thanks @jerelmiller! - Introduce the newremoveTypenameFromVariableslink. This link will automatically remove__typenamefields fromvariablesfor all operations. This link can be configured to exclude JSON-scalars for scalars that utilize__typename.This change undoes some work from #10724 where
__typenamewas automatically stripped for all operations with no configuration. This was determined to be a breaking change and therefore moved into this link.For a detailed explanation of
removeTypenameFromVariables, see its API reference.
New skipToken sentinel ⏭️
-
#11112
b4aefcfe9Thanks @jerelmiller! - Adds support for askipTokensentinel that can be used asoptionsinuseSuspenseQueryanduseBackgroundQueryto skip execution of a query. This works identically to theskipoption but is more type-safe and as such, becomes the recommended way to skip query execution. As such, theskipoption has been deprecated in favor ofskipToken.We are considering the removal of the
skipoption fromuseSuspenseQueryanduseBackgroundQueryin the next major. We are releasing with it now to make migration fromuseQueryeasier and makeskipTokenmore discoverable.useSuspenseQueryimport { skipToken, useSuspenseQuery } from "@apollo/client"; const id: number | undefined; const { data } = useSuspenseQuery( query, id ? { variables: { id } } : skipToken );useBackgroundQueryimport { skipToken, useBackgroundQuery } from "@apollo/client"; function Parent() { const [queryRef] = useBackgroundQuery( query, id ? { variables: { id } } : skipToken ); return queryRef ? <Child queryRef={queryRef} /> : null; } function Child({ queryRef }: { queryRef: QueryReference<TData> }) { const { data } = useReadQuery(queryRef); }For a detailed explanation of
skipToken, see its API reference.
New error extraction mechanism, smaller bundles 📉
-
#10887
f8c0b965dThanks @phryneas! - Add a new mechanism for Error Extraction to reduce bundle size by including error message texts on an opt-in basis.By default, errors will link to an error page with the entire error message. This replaces "development" and "production" errors and works without additional bundler configuration.
Bundling the text of error messages and development warnings can be enabled as follows:
import { loadErrorMessages, loadDevMessages } from "@apollo/client/dev"; if (process.env.NODE_ENV !== "production") { loadErrorMessages(); loadDevMessages(); }For a detailed explanation, see our reference on reducing bundle size.
New @nonreactive directive 🎬
-
#10722
c7e60f83dThanks @benjamn! - Implement a@nonreactivedirective for selectively skipping reactive comparisons of query result subtrees.The
@nonreactivedirective can be used to mark query fields or fragment spreads and is used to indicate that changes to the data contained within the subtrees marked@nonreactiveshould not trigger re-rendering. This allows parent components to fetch data to be rendered by their children without re-rendering themselves when the data corresponding with fields marked as@nonreactivechange.Consider an
Appcomponent that fetches and renders a list of ski trails:View code 🎿
const TrailFragment = gql` fragment TrailFragment on Trail { name status } `; const ALL_TRAILS = gql` query allTrails { allTrails { id ...TrailFragment @nonreactive } } ${TrailFragment} `; function App() { const { data, loading } = useQuery(ALL_TRAILS); return ( <main> <h2>Ski Trails</h2> <ul> {data?.trails.map((trail) => ( <Trail key={trail.id} id={trail.id} /> ))} </ul> </main> ); }The
Trailcomponent renders a trail's name and status and allows the user to execute a mutation to toggle the status of the trail between"OPEN"and"CLOSED":View code 🎿
const Trail = ({ id }) => { const [updateTrail] = useMutation(UPDATE_TRAIL); const { data } = useFragment({ fragment: TrailFragment, from: { __typename: "Trail", id, }, }); return ( <li key={id}> {data.name} - {data.status} <input checked={data.status === "OPEN" ? true : false} type="checkbox" onChange={(e) => { updateTrail({ variables: { trailId: id, status: e.target.checked ? "OPEN" : "CLOSED", }, }); }} /> </li> ); };Notice that the
Trailcomponent isn't receiving the entiretrailobject via props, only theidwhich is used along with the fragment document to create a live binding for each trail item in the cache. This allows eachTrailcomponent to react to the cache updates for a single trail independently. Updates to a trail'sstatuswill not cause the parentAppcomponent to rerender since the@nonreactivedirective is applied to theTrailFragmentspread, a fragment that includes thestatusfield.For a detailed explanation, see our
@nonreactivereference and @alessbell's post on the Apollo blog about using@nonreactivewithuseFragment.
Abort the AbortController signal more granularly 🛑
-
#11040
125ef5b2aThanks @phryneas! -HttpLink/BatchHttpLink: Abort theAbortControllersignal more granularly.Before this change, when
HttpLink/BatchHttpLinkcreated anAbortControllerinternally, the signal would always be.aborted after the request was completed. This could cause issues with Sentry Session Replay and Next.js App Router Cache invalidations, which just replayed the fetch with the same options - including the cancelledAbortSignal.With this change, the
AbortControllerwill only be.abort()ed by outside events, not as a consequence of the request completing.
useFragment drops its experimental label 🎓
-
#10916
ea75e18deThanks @alessbell! - Remove experimental labels.useFragment, introduced in3.7.0asuseFragment_experimental, is no longer an experimental API 🎉 We've removed the_experimentalsuffix from its named export and have made a number of improvements.For a detailed explanation, see our
useFragmentreference and @alessbell's post on the Apollo blog about usinguseFragmentwith@nonreactivefor improved performance when rendering lists.useFragmentimprovements-
#10765
35f36c5aaThanks @phryneas! - More robust types for thedataproperty onUseFragmentResult. When a partial result is given, the type is now correctly set toPartial<TData>. -
#11083
f766e8305Thanks @phryneas! - Adjust the rerender timing ofuseQueryto more closely align withuseFragment. This means that cache updates delivered to both hooks should trigger renders at relatively the same time. Previously, theuseFragmentmight rerender much faster leading to some confusion. -
#10836
6794893c2Thanks @phryneas! - Remove the deprecatedreturnPartialDataoption fromuseFragmenthook.
-
More Minor Changes
-
#10895
e187866fdThanks @Gelio! - Add generic type parameter for the entity modified incache.modify. Improves TypeScript type inference for that type's fields and values of those fields.Example:
cache.modify<Book>({ id: cache.identify(someBook), fields: { title: (title) => { // title has type `string`. // It used to be `any`. }, => { // author has type `Reference | Book["author"]`. // It used to be `any`. }, }, }); -
#10895
e187866fdThanks @Gelio! - Use unique opaque types for theDELETEandINVALIDATEApollo cache modifiers.This increases type safety, since these 2 modifiers no longer have the
anytype. Moreover, it no longer triggers the@typescript-eslint/no-unsafe-returnrule. -
#10340
4f73c5ca1Thanks @alessbell! - Avoid callinguseQueryonCompletedfor cache writes -
#10527
0cc7e2e19Thanks @phryneas! - Remove thequery/mutation/subscriptionoption from hooks that already take that value as their first argument. -
#10506
2dc2e1d4fThanks @phryneas! - prevent accidental widening of inferredTDataandTVariablesgenerics for query hook option arguments -
#10521
fbf729414Thanks @benjamn! - Simplify__DEV__polyfill to use imports instead of global scope -
#10994
2ebbd3abbThanks @phryneas! - Add .js file extensions to imports in src and dist/*/.d.ts -
#11045
9c1d4a104Thanks @jerelmiller! - When changing variables back to a previously used set of variables, do not automatically cache the result as part of the query reference. Instead, dispose of the query reference so that theInMemoryCachecan determine the cached behavior. This means that fetch policies that would guarantee a network request are now honored when switching back to previously used variables. -
#11058
89bf33c42Thanks @phryneas! - (Batch)HttpLink: PropagateAbortErrors to the user when a user-providedsignalis passed to the link. Previously, these links would swallow allAbortErrors, potentially causing queries and mutations to never resolve. As a result of this change, users are now expected to handleAbortErrors when passing in a user-providedsignal. -
#10346
3bcfc42d3Thanks @jerelmiller! - Add the ability to allow@clientfields to be sent to the link chain. -
#10567
c2ce6496cThanks @benjamn! - AllowApolloCacheimplementations to specify default value forassumeImmutableResultsclient option, improving performance for applications currently usingInMemoryCachewithout configuringnew ApolloClient({ assumeImmutableResults: true }) -
#10915
3a62d8228Thanks @phryneas! - Changes how development-only code is bundled in the library to more reliably enable consuming bundlers to reduce production bundle sizes while keeping compatibility with non-node environments.
Patch Changes
-
#11086
0264fee06Thanks @jerelmiller! - Fix an issue where a call torefetch,fetchMore, or changingskiptofalsethat returned a result deeply equal to data in the cache would get stuck in a pending state and never resolve. -
#11053
c0ca70720Thanks @phryneas! - AddSuspenseCacheas a lazy hidden property on ApolloClient. This means thatSuspenseCacheis now an implementation details of Apollo Client and you no longer need to manually instantiate it and no longer need to pass it intoApolloProvider. Trying to instantiate aSuspenseCacheinstance in your code will now throw an error. -
#11115
78739e3efThanks @phryneas! - Enforceexport typefor all type-level exports. -
#11027
e47cfd04eThanks @phryneas! - Prevents the DevTool installation warning to be turned into a documentation link. -
#10594
f221b5e8fThanks @phryneas! - Add asuspenseCacheoption touseSuspenseQuery -
#10700
12e37f46fThanks @jerelmiller! - Add aqueryKeyoption touseSuspenseQuerythat allows the hook to create a unique subscription instance. -
#10724
e285dfd00Thanks @jerelmiller! - Automatically strips__typenamefields fromvariablessent to the server when usingHttpLink,BatchHttpLink, orGraphQLWsLink. This allows GraphQL data returned from a query to be used as an argument to a subsequent GraphQL operation without the need to strip the__typenamein user-space. -
#10957
445164d21Thanks @phryneas! - UseReact.versionas key for shared Contexts. -
#10635
7df51ee19Thanks @jerelmiller! - Fix an issue where cache updates would not propagate touseSuspenseQuerywhile in strict mode. -
#11013
5ed2cfdafThanks @alessbell! - Make private fieldsinFlightLinkObservablesandfetchCancelFnsprotected in QueryManager in order to make types available in@apollo/experimental-nextjs-app-supportpackage when extending theApolloClientclass. -
#10869
ba1d06166Thanks @phryneas! - Ensure Context value stability when rerendering ApolloProvider with the sameclientand/orsuspenseCacheprop -
#11103
e3d611dafThanks @caylahamann! - Fixes a bug inuseMutationso thatonErroris called when an error is returned from the request witherrorPolicyset to 'all' . -
#10657
db305a800Thanks @jerelmiller! - ReturnnetworkStatusin theuseSuspenseQueryresult. -
#10937
eea44eb87Thanks @jerelmiller! - MovesDocumentTransformto theutilitiessub-package to avoid a circular dependency between thecoreandcachesub-packages. -
#10951
2e833b2caThanks @alessbell! - ImproveuseBackgroundQuerytype interface -
#10651
8355d0e1eThanks @jerelmiller! - Fixes an issue whereuseSuspenseQuerywould not respond to cache updates when using a cache-firstfetchPolicyafter the hook was mounted with data already in the cache. -
#11026
b8d405eeeThanks @phryneas! - Store React.Context instance mapped by React.createContext instance, not React.version. UsingReact.versioncan cause problems withpreact, as multiple versions ofpreactwill all identify themselves as React17.0.2. -
#11000
1d43ab616Thanks @phryneas! - Useimport * as Reacteverywhere. This prevents an error when importing@apollo/clientin a React Server component. (see #10974) -
#10852
27fbdb3f9Thanks @phryneas! - Chore: Add ESLint rule for consistent type imports, apply autofix -
#10999
c1904a78aThanks @phryneas! - Fix a bug inQueryReferencewherethis.resolveorthis.rejectmight be executed even ifundefined. -
#10940
1d38f128fThanks @jerelmiller! - Add support for theskipoption inuseBackgroundQueryanduseSuspenseQuery. Setting this option totruewill avoid a network request. -
#10672
932252b0cThanks @jerelmiller! - Fix the compatibility betweenuseSuspenseQueryand React'suseDeferredValueandstartTransitionAPIs to allow React to show stale UI while the changes to the variable cause the component to suspend.Breaking change
nextFetchPolicysupport has been removed fromuseSuspenseQuery. If you are using this option, remove it, otherwise it will be ignored. -
#10964
f33171506Thanks @alessbell! - Fixes a bug inBatchHttpLinkthat removed variables from all requests by default. -
#10633
90a06eeebThanks @benjamn! - Fix type policy inheritance involving fuzzypossibleTypes -
#10754
64b304862Thanks @sincraianul! - FixincludeUnusedVariablesoption not working withBatchHttpLink -
#11018
5618953f3Thanks @jerelmiller! -useBackgroundQuerynow uses its own options type calledBackgroundQueryHookOptionsrather than reusingSuspenseQueryHookOptions. -
#11035
a3ab7456dThanks @jerelmiller! - Incrementally re-render deferred queries after callingrefetchor settingskiptofalseto match the behavior of the initial fetch. Previously, the hook would not re-render until the entire result had finished loading in these cases. -
#10399
652a1ae08Thanks @alessbell! - Silence useLayoutEffect warning when useSuspenseQuery runs on server -
#10919
f796ce1acThanks @jerelmiller! - Fix an issue when using a link that relied onoperation.getContextandoperation.setContextwould error out when it was declared after theremoveTypenameFromVariableslink. -
#10968
b102390b2Thanks @phryneas! - Use printed query for query deduplication. Cacheprintcalls for GraphQL documents to speed up repeated operations. -
#11071
4473e925aThanks @jerelmiller! - #10509 introduced some helpers for determining the type of operation for a GraphQL query. This imported theOperationTypeNodefrom graphql-js which is not available in GraphQL 14. To maintain compatibility with graphql-js v14, this has been reverted to use plain strings. -
#10766
ffb179e55Thanks @jerelmiller! - More robust typings for thedataproperty returned fromuseSuspenseQuerywhen usingreturnPartialData: trueor anerrorPolicyofallorignore.TDatanow defaults tounknowninstead ofany. -
#10401
3e5b41a75Thanks @jerelmiller! - Always throw network errors inuseSuspenseQueryregardless of the seterrorPolicy. -
#10877
f40248598Thanks @phryneas! - Change an import inuseQueryanduseMutationthat added an unnecessary runtime dependency on@apollo/client/core. This drastically reduces the bundle size of each the hooks. -
#10656
54c4d2f3cThanks @jerelmiller! - Ensurerefetch,fetchMore, andsubscribeToMorefunctions returned byuseSuspenseQueryare referentially stable between renders, even asdatais updated. -
#10324
95eb228beThanks @jerelmiller! - Add@defersupport touseSuspenseQuery. -
#10888
1562a2f5aThanks @alessbell! - Updates dependency versions inpackage.jsonby bumping:@wry/contextto^0.7.3@wry/equalityto^0.5.6@wry/trieto^0.4.3optimismto^0.17.4
to 1. fix sourcemap warnings and 2. a Codesandbox sandpack (in-browser) bundler transpilation bug with an upstream optimism workaround.
-
#11010
1051a9c88Thanks @alessbell! - Hide queryRef in a Symbol inuseBackgroundQuerys return value. -
#10758
9def7421fThanks @phryneas! - useReact.usewhere available -
#11032
6a4da900aThanks @jerelmiller! - Throw errors inuseSuspenseQueryfor errors returned in incremental chunks whenerrorPolicyisnone. This provides a more consistent behavior of theerrorPolicyin the hook.Potentially breaking change
Previously, if you issued a query with
@deferand relied onerrorPolicy: 'none'to set theerrorproperty returned fromuseSuspenseQuerywhen the error was returned in an incremental chunk, this error is now thrown. Switch theerrorPolicytoallto avoid throwing the error and instead return it in theerrorproperty. -
#10960
ee407ef97Thanks @alessbell! - Adds support forreturnPartialDataandrefetchWritePolicyoptions inuseBackgroundQueryhook. -
#10809
49d28f764Thanks @jerelmiller! - Fixed the ability to userefetchandfetchMorewith React'sstartTransition. The hook will now behave correctly by allowing React to avoid showing the Suspense fallback when these functions are wrapped bystartTransition. This change deprecates thesuspensePolicyoption in favor ofstartTransition. -
#11082
0f1cde3a2Thanks @phryneas! - Restore Apollo Client 3.7getApolloContextbehaviour -
#10969
525a9317aThanks @phryneas! - Slightly decrease bundle size and memory footprint ofSuspenseCacheby changing how cache entries are stored internally. -
#11025
6092b6edfThanks @jerelmiller! -useSuspenseQueryanduseBackgroundQuerywill now properly apply changes to its options between renders. -
#10872
96b4f8837Thanks @phryneas! - The "per-React-Version-Singleton" ApolloContext is now stored onglobalThis, notReact.createContext, and throws an error message when accessed from React Server Components. -
#10450
f8bc33387Thanks @jerelmiller! - Add support for thesubscribeToMoreandclientfields returned in theuseSuspenseQueryresult.
3.7.17
Patch Changes
- #10631
b93388d75Thanks @phryneas! - ObservableQuery.getCurrentResult: skip the cache if the running query should not access the cache
3.7.16
Patch Changes
-
#10806
cb1540504Thanks @phryneas! - Fix a bug inPersistedQueryLinkthat would cause it to permanently skip persisted queries after a 400 or 500 status code. -
#10807
b32369592Thanks @phryneas! -PersistedQueryLinkwill now also check for error codes inextensions. -
#10982
b9be7a814Thanks @sdeleur-sc! - UpdaterelayStylePaginationto avoid populatingstartCursorwhen only a single cursor is present under theedgesfield. Use that cursor only as theendCursor. -
#10962
772cfa3cbThanks @jerelmiller! - RemoveuseGETForQueriesoption inBatchHttpLink.Optionstype since it is not supported.
3.7.15
Patch Changes
-
#10891
ab42a5c08Thanks @laverdet! - Fixes a bug in how multipart responses are read when using@defer. When reading a multipart body,HttpLinkno longer attempts to parse the boundary (e.g."---"or other boundary string) within the response data itself, only when reading the beginning of each mulitpart chunked message. -
#10789
23a4e1578Thanks @phryneas! - Fix a bug where other fields could be aliased to__typenameorid, in which case an incoming result would be merged into the wrong cache entry.
3.7.14
Patch Changes
-
#10764
1b0a61fe5Thanks @phryneas! - DeprecateuseFragmentreturnPartialDataoption -
#10810
a6252774fThanks @dleavitt! - Fix type signature ofServerError.In <3.7
HttpLinkandBatchHttpLinkwould return aServerError.messageof e.g."Unexpected token 'E', \"Error! Foo bar\" is not valid JSON"and aServerError.resultofundefinedin the case where a server returned a >= 300 response code with a response body containing a string that could not be parsed as JSON.In >=3.7,
messagebecame e.g.Response not successful: Received status code 302andresultbecame the string from the response body, however the type inServerError.resultwas not updated to include thestringtype, which is now properly reflected.
3.7.13
Patch Changes
-
#10805
a5503666cThanks @phryneas! - Fix a potential memory leak in SSR scenarios when manypersistedQueryinstances were created over time. -
#10718
577c68bddThanks @Hsifnus! - Delay Concast subscription teardown slightly inuseSubscriptionto prevent unexpected Concast teardown when oneuseSubscriptionhook tears down its in-flight Concast subscription immediately followed by anotheruseSubscriptionhook reusing and subscribing to that same Concast
3.7.12
Patch Changes
- #10735
895bcdcffThanks @alessbell! - If a multipart chunk contains onlyhasNext: false, immediately complete the observable.
3.7.11
Patch Changes
-
#10586
4175af594Thanks @alessbell! - Improve WebSocket error handling for genericEventreceived on error. For more information see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event. -
#10411
152baac34Thanks @lovasoa! - Simplify error message generation and make 'undefined' an impossible message string. -
#10592
cdb98ae08Thanks @alessbell! - Adds support for multipart subscriptions inHttpLink. -
#10698
38508a251Thanks @jerelmiller! - Changes the behavior ofuseLazyQueryintroduced in #10427 where unmounting a component before a query was resolved would reject the promise with an abort error. Instead, the promise will now resolve naturally with the result from the request.Other notable fixes:
- Kicking off multiple requests in parallel with the execution function will now ensure each returned promise is resolved with the data from its request. Previously, each promise was resolved with data from the last execution.
- Re-rendering
useLazyQuerywith a different query document will now ensure the execution function uses the updated query document. Previously, only the query document rendered the first time would be used for the request.
-
#10660
364bee98fThanks @alessbell! - Upgrades TypeScript to v5. This change is fully backward-compatible and transparent to users. -
#10597
8fb9d190dThanks @phryneas! - Fix a bug where an incoming cache update could prevent future updates from the active link. -
#10629
02605bb3cThanks @phryneas! -useQuery: delay unsubscribe to fix race conditions
3.7.10
Patch Changes
-
#9438
52a9c8ea1Thanks @dciesielkiewicz! - Ensure theclientoption passed touseMutation's execute function is used when provided. Previously this option was ignored. -
#9124
975b923c0Thanks @andrebrantom! - MakeApolloClient.writeQueryandApolloClient.writeFragmentbehave more likecache.writeQueryandcache.writeFragmentby returning the reference returned by the cache.
3.7.9
Patch Changes
-
#10560
a561ecf43Thanks @benjamn! - Keep__typenamefragment when it does not contain@clientdirective and strip out inline fragments which use a@clientdirective. Thanks @Gazler and @mtsmfm! -
#10560
251a12806Thanks @benjamn! - RefactorremoveDirectivesFromDocumentto fix AST ordering sensitivities and avoid 1/3 AST traversals, potentially improving performance for large queries
3.7.8
Patch Changes
-
#7555
45562d6faThanks @TheCeloReis! - AddsTVariablesgeneric toGraphQLRequestandMockedResponseinterfaces. -
#10526
1d13de4f1Thanks @benjamn! - Tolerate undefinedconcast.sourcesifcompletecalled earlier thanconcast.start -
#10497
8a883d8a1Thanks @nevir! - UpdateSingleExecutionResultandIncrementalPayload'sdatatypes such that they no longer includeundefined, which was not a valid runtime value, to fix errors when TypeScript'sexactOptionalPropertyTypesis enabled.
3.7.7
Patch Changes
-
#10502
315faf9caThanks @jerelmiller! - Log a warning to the console when a mock passed toMockedProviderorMockLinkcannot be matched to a query during a test. This makes it easier to debug user errors in the mock setup, such as typos, especially if the query under test is using anerrorPolicyset toignore, which makes it difficult to know that a match did not occur. -
#10499
9e54f5dfaThanks @phryneas! - Allow the execution function returned byuseLazyQueryto change the query. -
#10362
14a56b105Thanks @mccraveiro! - Fix error when server returns an error and we are also querying for a local field
3.7.6
Patch Changes
-
#10470
47435e879Thanks @alessbell! - Bumps TypeScript to4.9.4(previously4.7.4) and updates types to account for changes in TypeScript 4.8 by propagating contstraints on generic types. Technically this makes some types stricter as attempting to passnull|undefinedinto certain functions is now disallowed by TypeScript, but these were never expected runtime values in the first place. This should only affect you if you are wrapping functions provided by Apollo Client with your own abstractions that pass in their generics as type arguments, in which case you might get an error likeerror TS2344: Type 'YourGenericType' does not satisfy the constraint 'OperationVariables'. In that case, make sure thatYourGenericTypeis restricted to a type that only accepts objects viaextends, likeRecord<string, any>or@apollo/client'sOperationVariables:import { QueryHookOptions, QueryResult, useQuery, + OperationVariables, } from '@apollo/client'; - export function useWrappedQuery<T, TVariables>( + export function useWrappedQuery<T, TVariables extends OperationVariables>( query: DocumentNode, queryOptions: QueryHookOptions<T, TVariables> ): QueryResult<T, TVariables> { const [execute, result] = useQuery<T, TVariables>(query); } -
#10408
55ffafc58Thanks @zlrlo! - fix: modify BatchHttpLink to have a separate timer for each different batch key -
#9573
4a4f48ddaThanks @vladar! - Improve performance of local resolvers by only executing selection sets that contain an@clientdirective. Previously, local resolvers were executed even when the field did not contain@client. While the result was properly discarded, the unncessary work could negatively affect query performance, sometimes signficantly.
3.7.5
Patch Changes
-
#10458
b5ccef229Thanks @lennyburdette! - PassesgetServerSnapshottouseSyncExternalStoreso that it doesn't trigger aMissing getServerSnapshoterror when usinguseFragment_experimentalon the server. -
#10471
895ddcb54Thanks @alessbell! - More robust type definition forheadersproperty passed tocreateHttpLink -
#10321
bbaa3ef2dThanks @alessbell! - Refetch should not return partial data witherrorPolicy: noneandnotifyOnNetworkStatusChange: true. -
#10469
328c58f90Thanks @jerelmiller! - Add generic type defaults when usinguseFragmentto allow passingTDatadirectly to the function without needing to specifyTVars.
3.7.4
Patch Changes
-
#10427
28d909cffThanks @jerelmiller! - Ensure in-flight promises executed byuseLazyQueryare rejected whenuseLazyQueryunmounts. -
#10383
5c5ca9b01Thanks @jerelmiller! - Ensure theonErrorcallback is called when theerrorPolicyis set to "all" and partial data is returned. -
#10425
86e35a6d2Thanks @jerelmiller! - Prefer theonErrorandonCompletedcallback functions passed to the execute function returned fromuseMutationinstead of calling both callback handlers.
3.7.3
Patch Changes
-
#10334
7d923939dThanks @jerelmiller! - Better handle deferred queries that have cached or partial cached data for them -
#10368
46b58e976Thanks @alessbell! - Fix: unblocks support for defer in mutationsIf the
@deferdirective is present in the document passed tomutate, the Promise will resolve with the final merged data after the last multipart chunk has arrived in the response.
3.7.2
Patch Changes
-
Only show dev tools suggestion in the console when
connectToDevToolsistrue.
@chris110408 in #10258 -
Pass
TCachegeneric toMutationHookOptionsfor better type support inuseMutation.
@igrlk in #10223 -
Add
nameproperty toApolloErrorto ensure better type safety and help error reporting tools better identify the error.
@aaronadamsCA in #9323 -
Export a
ModifierDetailstype for thedetailsparameter of aModifierfunction.
@KeithGillette in #7133 -
Revert use of
cloneDeepto clone options when fetching queries.
@MrDoomBringer in #10215
3.7.1
Patch Changes
-
Fix issue where
loadingremainstrueafterobserver.refetchis called repeatedly with different variables when the same data are returned.
@alessbell in #10143 -
Fix race condition where
useFragment_experimentalcould receive cache updates before initially callingcache.watchinuseEffect.
@benjamn in #10212
3.7.0
Minor Changes
-
Implement preview support for the
@deferdirective.
@alessbell and @benjamn in #10018 -
Implement
useFragment_experimentalhook, which represents a lightweight live binding into theApolloCache, and never triggers network requests of its own.
@benjamn in #8782 -
Allow registering named fragments with
InMemoryCacheto support using...NamedFragmentin queries without redeclaringNamedFragmentrepeatedly in every query that uses it.
@benjamn in #9764 -
Support
onErrorcallback foruseSubscriptionhook.
@jeroenvisser101 in #9495 -
Implement
preserveHeaderCaseoption forhttpcontext object, enabling preserved header capitalization for non-http-spec-compliant servers.
@mrdoombringer in #9891
Patch Changes
-
Delay calling
onCompletedandonErrorcallbacks passed touseQueryusingPromise.resolve().then(() => ...)to fix issue #9794.
@dylanwulf in #9823 -
Replace
concast.cleanupmethod with simplerconcast.beforeNextAPI, which promises to call the given callback function just before the next result/error is delivered. In addition,concast.removeObserverno longer takes aquietly?: booleanparameter, since that parameter was partly responsible for cleanup callbacks sometimes not getting called.
@benjamn in #9718 -
Allow preserving header name capitalization when creating an
HttpLinkwithcreateHttpLink({ uri, preserveHeaderCase: true }). Otherwise, header names are converted to lowercase to prevent case-sensitivity bugs.
@MrDoomBringer in #9891 -
Make queries with a
pollIntervalrespect theno-cachefetch policy, instead of writing polled results into the cache.
@MrDoomBringer in #10020 -
Deprecate the
onSubscriptionDatacallback in favor of a newonDatacallback for theuseSubscriptionhook. Deprecate theonSubscriptionCompletecallback in favor of a newonCompletecallback for theuseSubscriptionhook.
@jerelmiller in #10134
Potentially disruptive
- The optional
subscribeAndCounttesting utility exported from@apollo/client/testing/corenow takes a single genericTResulttype parameter, instead ofTData. This type will typically be inferred from theobservableargument type, but if you have any explicit calls tosubscribeAndCount<TData>(...)in your own codebase, you may need to adjust those calls accordingly.
@benjamn in #9718
Apollo Client 3.6.10 (2022-09-29)
Improvements
- The client options (
variables,context, etc.) used formutationcalls are now available as the second argument to theonCompletedandonErrorcallback functions.
@MrDoomBringer in #10052
Apollo Client 3.6.9 (2022-06-21)
Bug Fixes
- Leave
fetchPolicyunchanged whenskip: true(or in standby) andnextFetchPolicyis available, even ifvariableschange.
@benjamn in #9823
Apollo Client 3.6.8 (2022-06-10)
Bug Fixes
-
Fix incorrect
variablespassed inFieldFunctionOptionsfor nestedreadFieldcalls inreadandmergefunctions.
@stardustxx in #9808 -
Improve repository build scripts to work better on Windows.
@dylanwulf in #9805 -
Ensure
useQuery(query, { skip: true }).called === falserather than always returningcalledastrue.
@KucharskiPiotr in #9798 -
Allow abandoned
reobserverequests to unsubscribe from their underlyingObservable.
@javier-garcia-meteologica in #9791
Apollo Client 3.6.7 (2022-06-10)
Bug Fixes
- Fix regression (introduced in v3.6.0) that caused
BatchHttpLinkto discard pending batched queries on early completion of the underlyingObservable.
@benjamn in #9793
Apollo Client 3.6.6 (2022-05-26)
Bug Fixes
- Allow
useLazyQuery(query, { defaultOptions })to benefit fromdefaultOptions.variablesandclient.defaultOptions.watchQuery.variablesmerging.
@benjamn in #9762
Apollo Client 3.6.5 (2022-05-23)
Bug Fixes
-
Restore pre-v3.6
variablesreplacement behavior ofObservableQuery#reobservemethod, fixing a regression that prevented removal of variables.
@benjamn in #9741 -
Preserve
previousDataeven when different query or client provided touseQuery, instead of resettingpreviousDatato undefined in those cases, matching behavior prior to v3.6.0.
@benjamn in #9734 -
Fix bug where
onCompleted()andonError()are stale foruseMutation().
@charle692 in #9740 -
Limit scope of
DeepMergerobject reuse, and avoid usingObject.isFrozen, which can introduce differences between development and production if objects that were frozen usingObject.freezein development are left unfrozen in production.
@benjamn in #9742 -
Properly merge
variablesfrom originaluseLazyQuery(query, { variables })withvariablespassed to execution function.
@benjamn in #9758
Apollo Client 3.6.4 (2022-05-16)
Bug Fixes
-
Guarantee
Concastcleanup withoutObservable cancelled prematurelyrejection, potentially solving long-standing issues involving that error.
@benjamn in #9701 -
Ensure
useSubscriptionsubscriptions are properly restarted after unmounting/remounting by React 18 in<StrictMode>.
@kazekyo in #9707
Improvements
-
Internalize
useSyncExternalStoreshim, for more control thanuse-sync-external-storeprovides, fixing some React Native issues.
@benjamn in #9675 and #9709 -
Provide
@apollo/client/**/*.cjs.native.jsversions of every@apollo/client/**/*.cjsbundle (including dependenciests-invariantandzen-observable-ts) to help React Native's Metro bundler automatically resolve CommonJS entry point modules. These changes should render unnecessary the advice we gave in the v3.5.4 section below aboutmetro.config.js.
@benjamn in #9716 -
Handle falsy
incomingdata more gracefully inoffetLimitPagination().mergefunction.
@shobhitsharma in #9705
Apollo Client 3.6.3 (2022-05-05, only tagged next on npm)
Bug Fixes
-
Simplify
useQuery(query, { defaultOptions })default options processing in order to fix bug whereskip: truequeries failed to execute upon switching toskip: false.
@benjamn in #9665 -
Add tests of skipping/unskipping and
useLazyQuerywithdefaultOptions, and fix a bug causing duplicate requests.
@benjamn in #9666 -
Update
ts-invariantto version 0.10.2 to fix source map warnings.
@benjamn in #9672 -
Test that
useQueryqueries withskip: truedo not stall server-side rendering.
@nathanmarks and @benjamn in #9677 -
Prevent
useLazyQueryfrom making duplicate requests when its execution function is first called, and stop rejecting thePromiseit returns whenresult.erroris defined.
@benjamn in #9684 -
Fix issue with
useQueryreturningloading: truestate during server-side rendering withskip: true.
@nathanmarks in #9679
Apollo Client 3.6.2 (2022-05-02)
Bug Fixes
- Pass
getServerSnapshotfunction touseSyncExternalStorein addition togetSnapshot, though the two functions behave identically. This change should fix/unbreak React 18 server rendering.
@hungphongbk in #9652
Improvements
- Consider
networkError.result.errorsin addition toresult.errorsinPersistedQueryLink.
@redaid113 and @benjamn in #9410
Apollo Client 3.6.1 (2022-04-28)
Bug Fixes
- Remove recently-added, internal
fetchBlockingPromiseoption from theWatchQueryOptionsinterface, due to regressions.
@benjamn in #9504
Apollo Client 3.6.0 (2022-04-26)
Potentially disruptive changes
-
Calling
fetchMorefor queries using thecache-and-networkornetwork-onlyfetch policies will no longer trigger additional network requests when cache results are complete. Instead, those complete cache results will be delivered as if using thecache-firstfetch policy.
@benjamn in #9504 -
Reimplement
useQueryanduseLazyQueryto use the proposeduseSyncExternalStoreAPI from React 18.
@brainkim and @benjamn in #8785 and #9596 -
Fixed bug where the
useLazyQueryexecution function would always use therefetchmethod ofObservableQuery, instead of properly reapplying the currentfetchPolicyusing thereobservemethod.
@benjamn in #9564Since this
reobservemethod is useful and used internally, we have now exposed it asuse[Lazy]Query(...).reobserve(which optionally takes aPartial<WatchQueryOptions>of new options), to supplement the existingrefetchmethod. Note thatreobservepermanently updates thevariablesand other options of theObservableQuery, unlikerefetch({ ...variables }), which does not save thosevariables. -
The internal use of
options.fetchBlockingPromisebyuseQueryanduseLazyQuerymay slightly delay the delivery of network results, compared to previous versions of Apollo Client. Since network results are already delivered asynchronously, these timing differences should not be disruptive in most cases. Nevertheless, please open an issue if the timing differences are a problem for you (and you have no easy workaround).
@benjamn in #9599
React 18
In both its peerDependencies and its internal implementation, Apollo Client v3.6 should no longer prevent you from updating to React 18 in your applications.
Internally, we have refactored useQuery and useLazyQuery to be implemented in terms of React's new (shimmable) useSyncExternalStore hook, demonstrating Apollo Client can serve as an external store with a referentially stable, synchronous API, as needed by React.
As part of this refactoring, we also improved the behavior of useQuery and useLazyQuery when used in <React.StrictMode>, which double-renders components in development. While this double-rendering always results in calling useQuery twice, forcing Apollo Client to create and then discard an unnecessary ObservableQuery object, we now have multiple defenses in place against executing any network queries for the unused ObservableQuery objects.
In upcoming v3.6.x and v3.7 (beta) releases, we will be completely overhauling our server-side rendering utilities (getDataFromTree et al.), and introducing suspenseful versions of our hooks, to take full advantage of the new patterns React 18+ enables for data management libraries like Apollo Client.
Improvements
-
Allow
BatchLinkto cancel queued and in-flight operations.
@PowerKiKi and @benjamn in #9248 -
Add
GraphQLWsLinkin@apollo/client/link/subscriptions. This link is similar to the existingWebSocketLinkin@apollo/client/link/ws, but uses the newergraphql-wspackage and protocol instead of the oldersubscriptions-transport-wsimplementation. This functionality was technically first released in@apollo/client@3.5.10, but semantically belongs in the 3.6.0 minor version. @glasser in #9369 -
Allow passing
defaultOptionstouseQueryto avoid clobbering/resetting existing options whenuseQueryis called repeatedly.
@benjamn in #9563, superseding #9223 -
Provide additional context to
nextFetchPolicyfunctions to assist withfetchPolicytransitions. More details can be found in thenextFetchPolicydocumentation.
@benjamn in #9222 -
Remove nagging deprecation warning about passing an
options.updateQueryfunction tofetchMore.
@benjamn in #9504 -
Let
addTypenameToDocumenttake anyASTNode(includingDocumentNode, as before).
@benjamn in #9595 -
Set
useMutationinternalisMountedvariable totrueagain when component remounted.
@devpeerapong in #9561
Apollo Client 3.5.10 (2022-02-24)
Improvements
-
Add
GraphQLWsLinkin@apollo/client/link/subscriptions. This link is similar to the existingWebSocketLinkin@apollo/client/link/ws, but uses the newergraphql-wspackage and protocol instead of the oldersubscriptions-transport-wsimplementation.
@glasser in #9369Note from @benjamn: since
GraphQLWsLinkis new functionality, we would normally wait for the next minor version (v3.6), but we were asked to expedite this release. These changes are strictly additive/opt-in/backwards-compatible, so shipping them in a patch release (3.5.10) seems safe, if unusual.
Apollo Client 3.5.9 (2022-02-15)
Improvements
-
Interpret
keyFields: [...]andkeyArgs: [...]configurations inInMemoryCachetype/field policies asReadonlyArrays, since they are never mutated internally.
@julienfouilhe in #9339 -
Avoid declaring a global type for the
__DEV__constant, to avoid conflict with other such global declarations.
@benjamn in #9386
Bug Fixes
-
Fix
useSubscriptionexecutingskipped subscription when input changes.
@levrik in #9299 -
Fix partial data appearing in
useQuery().datawhennotifyOnNetworkStatusChange: true.
@brainkim in #9367 -
Prevent
Promises returned byuseLazyQueryexecute functions from causing unhandledPromiserejection errors if uncaught.
@brainkim in #9380
Apollo Client 3.5.8 (2022-01-24)
Bug Fixes
Bug Fixes (by @brainkim in #9328)
- Fix
refetch()not being called whenskipis true. - Fix the promise returned from the
useLazyQuery()execution function having stale variables. - Fix the promise returned from the
useLazyQuery()execution function not rejecting when a query errors.
Apollo Client 3.5.7 (2022-01-10)
Bug Fixes
-
Fix regression that prevented calling
onErrororonCompletedin some cases when usinguseQuery.
@mmahalwy in #9226 -
Make
useQueryrespectdefaultOptions.watchQuery.fetchPolicy.
@yasharzolmajdi in #9210
Apollo Client 3.5.6 (2021-12-07)
Bug Fixes (by @brainkim in #9144)
- Restores old behavior where the callback passed to
useMutation()is constant. - Fix
useMutation()callbacks having stale closures. - Fix
useQuery()variables being out of date.
Apollo Client 3.5.5 (2021-11-23)
Bug Fixes
- Remove
printer: Printerpositional parameter from publicly-exportedselectHttpOptionsAndBodyfunction, whose addition in #8699 was a breaking change (starting in Apollo Client 3.5.0) for direct consumers ofselectHttpOptionsAndBody.
@benjamn in #9103
Apollo Client 3.5.4 (2021-11-19)
Notices
⚠️ The following advice about
metro.config.jsshould no longer be necessary, as of Apollo Client v3.6.4.
-
[Relevant if you use Apollo Client with React Native] Since Apollo Client v3.5.0, CommonJS bundles provided by
@apollo/clientuse a.cjsfile extension rather than.cjs.js, so Node.js won't interpret them as ECMAScript modules. While this change should be an implementation detail, it may cause problems for the Metro bundler used by React Native, whoseresolver.sourceExtsconfiguration does not include thecjsextension by default.As a workaround until this issue is resolved, you can configure Metro to understand the
.cjsfile extension by creating ametro.config.jsfile in the root of your React Native project:// NOTE: No longer necessary in @apollo/client@3.6.4! const { getDefaultConfig } = require("metro-config"); const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues(); exports.resolver = { ...defaultResolver, sourceExts: [...defaultResolver.sourceExts, "cjs"], };
Improvements
-
Restore the ability to pass
onError()andonCompleted()to the mutation execution function.
@brainkim in #9076 -
Work around webpack 5 errors of the form
The request 'ts-invariant/process' failed to resolve only because it was resolved as fully specifiedby ensuring
import ... from 'ts-invariant/process'is internally written toimport ... from 'ts-invariant/process/index.js'.
@benjamn in #9083
Apollo Client 3.5.3 (2021-11-17)
-
Avoid rewriting non-relative imported module specifiers in
config/rewriteModuleIds.tsscript, thereby allowing bundlers to resolve those imports as they see fit.
@benjamn in #9073 -
Ensure only current file is matched when running VSCode debugger.
@eps1lon in #9050
Apollo Client 3.5.2 (2021-11-10)
- Fix
useMutationexecute function returning non-identical execution functions when passing similar options.
@brainkim in #9037
Apollo Client 3.5.1 (2021-11-09)
Apollo Client 3.5.0 (2021-11-08)
Improvements
-
Add
updateQueryandupdateFragmentmethods toApolloCache, simplifying commonreadQuery/writeQuerycache update patterns.
@wassim-k in #8382 -
Field directives and their arguments can now be included along with field argument names when using field policy
keyArgs: [...]notation. For example, if you have aQuery.feedfield that takes an argument calledtypeand uses a@connection(key:...)directive to keepfeeddata from different queries separate within the cache, you might configure both using the followingInMemoryCachefield policy:new InMemoryCache({ typePolicies: { Query: { fields: { feed: { keyArgs: ["type", "@connection", ["key"]], }, }, }, }, }); -
Report single
MissingFieldErrorinstead of a potentially very largeMissingFieldError[]array for incomplete cache reads, improving performance and memory usage.
@benjamn in #8734 -
When writing results into
InMemoryCache, each written object is now identified usingpolicies.identifyafter traversing the fields of the object (rather than before), simplifying identification and reducing duplicate work. If you have customkeyFieldsfunctions, they still receive the raw result object as their first parameter, but theKeyFieldsContextparameter now providescontext.storeObject(theStoreObjectjust processed byprocessSelectionSet) andcontext.readField(a helper function for reading fields fromcontext.storeObjectand anyReferences it might contain, similar toreadFieldforread,merge, andcache.modifyfunctions).
@benjamn in #8996 -
Ensure
cache.identifynever throws when primary key fields are missing, and include the source object in the error message whenkeyFieldsprocessing fails.
@benjamn in #8679 -
The
HttpLinkconstructor now accepts an optionalprintfunction that can be used to customize how GraphQLDocumentNodeobjects are transformed back into strings before they are sent over the network.
@sarahgp in #8699 -
Make
@apollo/client/testinga fully-fledged, independent entry point, instead of re-exporting@apollo/client/utilities/testing(which was never an entry point and no longer exists).
@benjamn in #8769 -
A new nested entry point called
@apollo/client/testing/corehas been created. Importing from this entry point instead of@apollo/client/testingexcludes any React-related dependencies.
@wassim-k in #8687 -
Make
cache.batchreturn the result of calling theoptions.updatefunction.
@benjamn in #8696 -
The
NetworkErrorandErrorResponsetypes have been changed to align more closely.
@korywka in #8424 -
Update
zen-observable-tsto eliminate transitive dependency on@types/zen-observable.
@benjamn in #8695
React Refactoring
Improvements (due to @brainkim in #8875):
- The
useLazyQueryfunction now returns a promise with the result. - The
useMutationresult now exposes a method which can be reset.
Bug Fixes (due to @brainkim in #8596):
- The
useQueryanduseLazyQueryhooks will now haveObservableQuerymethods defined consistently. - Calling
useLazyQuerymethods likestartPollingwill start the query. - Calling the
useLazyQueryexecution function will now behave more likerefetch.previousDatawill be preserved. standbyfetchPolicies will now act likeskip: truemore consistently.- Calling
refetchon a skipped query will have no effect (issue #8270). - Prevent
onErrorandonCompletedfunctions from firing continuously, and improving their polling behavior.
Apollo Client 3.4.17 (2021-11-08)
Improvements
- Allow
TOptions extends FieldFunctionOptionsto be passed as final (optional) type parameter ofFieldPolicytype.
@VictorGaiva in #9000
Apollo Client 3.4.16
Improvements
-
Prevent webpack from misresolving the
graphqlpackage as the local@apollo/client/utilities/globals/graphql.jsmodule whenmodule.exports.resolve.preferRelativeis enabled inwebpack.config.js.Note: if you encounter strange module resolution errors like
export 'isType' (imported as 'isType') was not found in 'graphql' (possible exports: removeTemporaryGlobals)please try removingpreferRelative: truefrom yourwebpack.config.jsfile, or find a way to disable that resolution behavior for packages withinnode_modules. -
Avoid importing
isTypefrom thegraphqlpackage internally, to prevent bundlers from including as much as 3.4kB of unnecessary code.
@benjamn in #8891 -
Make
client.resetStoreandclient.clearStorepass appropriatediscardWatchesoption tocache.reset.
@benjamn in #8873
Apollo Client 3.4.15
Bug Fixes
- Require calling
cache.reset({ discardWatches: true })to makecache.resetdiscardcache.watches, restoring behavior broken in v3.4.14 by #8826.
@benjamn in #8852
Apollo Client 3.4.14
Bug Fixes
-
Disable
InMemoryCacheresult object canonization by default, to prevent unexpected memory growth and/or reuse of object references, with multiple ways to reenable it (per-cache, per-query, or a mixture of both).
@benjamn in #8822 -
Clear
InMemoryCachewatchesset whencache.reset()called.
@benjamn in #8826 -
Stop excluding observerless queries from
refetchQueries: [...]selection.
@benjamn in #8825 -
Prevent optimistic cache evictions from evicting non-optimistic data.
@benjamn in #8829 -
Ensure
cache.broadcastWatchpasses all relevantWatchOptionstocache.diffasDiffOptions.
@benjamn in #8832
Apollo Client 3.4.13
Bug Fixes
-
Fix
componentDidUpatetypo inwithSubscriptionhigher-order component.
@YarBez in #7506 -
Fix internal
canUseSymbolimport within@apollo/client/utilitiesto avoid breaking bundlers/builds.
@benjamn in #8817 -
Tolerate unfreezable objects like
Uint8ArrayandBufferinmaybeDeepFreeze.
@geekuillaume and @benjamn in #8813
Apollo Client 3.4.12
Bug Fixes
-
Improve handling of falsy
existingand/orincomingparameters inrelayStylePaginationfield policy helper function.
@bubba and @benjamn in #8733 -
Associate Apollo context with
React.createContext(instead of using a localWeakMap) again, so multiple copies of@apollo/client(uncommon) can share the same context.
@benjamn in #8798
Apollo Client 3.4.11
Bug Fixes
- Fix Vite tree-shaking by calling the
checkDEV()function (at least once) in the module that exports it,@apollo/client/utilities/globals/index.ts.
@benjamn in #8767
Improvements
Documentation
- Upgrade docs theme for new Algolia-powered search experience.
@trevorblades in #8768
Apollo Client 3.4.10
Improvements
- Warn when calling
refetch({ variables })instead ofrefetch(variables), except for queries that declare a variable named$variables(uncommon).
@benjamn in #8702
Bug Fixes
-
Fix
ObservableQuery.getCurrentResult()returning cacheddatawith certain fetch policies.
@brainkim in #8718 -
Prevent
ssrMode/ssrForceFetchDelayfrom causing queries to hang.
@brainkim in #8709 -
Import
@apollo/client/utilities/globalsinternally wherever__DEV__is used, not just in@apollo/client/**/index.jsentry points.
@benjamn in #8720
Apollo Client 3.4.9
Bug Fixes
-
Fix unhandled
Promiserejection warnings/errors whose message isObservable cancelled prematurely.
@benjamn in #8676 -
Enforce that
__DEV__is polyfilled by every@apollo/client/*entry point that uses it. This build step considers not only explicit__DEV__usage but also__DEV__references injected nearinvariant(...)andnew InvariantError(...)expressions.
@benjamn in #8689
Apollo Client 3.4.8
Bug Fixes
-
Fix error thrown by nested
keyFields: ["a", ["b", "c"], "d"]type policies when writing results into the cache where any of the key fields (.a,.a.b,.a.c, or.d) have been renamed by query field alias syntax.
@benjamn in #8643 -
Fix regression from PR #8422 (first released in
@apollo/client@3.4.0-rc.15) that causedresult.datato be set to undefined in some cases afterObservableQuery#getCurrentResultreads an incomplete result from the cache.
@benjamn in #8642
Apollo Client 3.4.7
Bug Fixes
- Fix accidental reuse of recycled
MergeTreeobjects inStoreWriterclass used byInMemoryCache.
@benjamn in #8618
Apollo Client 3.4.6
Improvements
-
Reevaluate
window.fetcheach timeHttpLinkuses it, if not configured usingoptions.fetch. This change enables a variety of strategies for instrumentingwindow.fetch, without requiring those strategies to run before@apollo/client/link/httpis first imported.
@benjamn in #8603 -
Clarify mutation
fetchPolicyoptions ("network-only"or"no-cache") usingMutationFetchPolicyunion type.
@benjamn in #8602
Bug Fixes
-
Restore full
@apollo/client/apollo-client.cjs.jsCommonJS bundle for older bundlers.Note that Node.js and CommonJS bundlers typically use the bundles specified by
"main"fields in our generatedpackage.jsonfiles, which are all independent and non-overlapping CommonJS modules. However,apollo-client.cjs.jsis just one big bundle, so mixing imports ofapollo-client.cjs.jswith the other CommonJS bundles is discouraged, as it could trigger the dual package hazard. In other words, please don't start usingapollo-client.cjs.jsif you're not already. -
Log
MissingFieldErrors inObservableQuery#getCurrentResultusinginvariant.debug, rather than reporting them viaresult.error.
@benjamn in #8604
Apollo Client 3.4.5
Bug Fixes
-
Fix double registration bug for mutation
refetchQueriesspecified using legacy one-timerefetchQueries: [{ query, variables }]style. Though the bug is fixed, we recommend usingrefetchQueries: [query]instead (when possible) to refetch an existing query using itsDocumentNode, rather than creating, executing, and then deleting a new query, as the legacy{ query, variables }style unfortunately does.
@benjamn in #8586 -
Fix
useQuery/useLazyQuerystalling when clients or queries change.
@brainkim in #8589
Apollo Client 3.4.4
Bug Fixes
- Revert accidental addition of
engines.npmsection to published version of@apollo/client/package.json.
@benjamn in #8578
Apollo Client 3.4.3
Bug Fixes
Apollo Client 3.4.2
Bug Fixes
- Use more default type parameters for mutation-related types in
react/types/types.ts, to provide smoother backwards compatibility for code using those types explicitly.
@benjamn in #8573
Apollo Client 3.4.1
Bug Fixes
- Initialize
stringifyCanonlazily, whencanonicalStringifyis first called, fixingUncaught ReferenceError: __DEV__ is not definederrors due to usage of__DEV__before declaration.
@benjamn in #8557
Apollo Client 3.4.0
New documentation
- Refetching queries with
client.refetchQueries.
@StephenBarlow and @benjamn in #8265
Improvements
-
InMemoryCachenow guarantees that any two result objects returned by the cache (fromreadQuery,readFragment, etc.) will be referentially equal (===) if they are deeply equal. Previously,===equality was often achievable for results for the same query, on a best-effort basis. Now, equivalent result objects will be automatically shared among the result trees of completely different queries. This guarantee is important for taking full advantage of optimistic updates that correctly guess the final data, and for "pure" UI components that can skip re-rendering when their input data are unchanged.
@benjamn in #7439 -
Mutations now accept an optional callback function called
onQueryUpdated, which will be passed theObservableQueryandCache.DiffResultobjects for any queries invalidated by cache writes performed by the mutation's finalupdatefunction. UsingonQueryUpdated, you can override the defaultFetchPolicyof the query, by (for example) callingObservableQuerymethods likerefetchto force a network request. This automatic detection of invalidated queries provides an alternative to manually enumerating queries using therefetchQueriesmutation option. Also, if you return aPromisefromonQueryUpdated, the mutation will automatically await thatPromise, rendering theawaitRefetchQueriesoption unnecessary.
@benjamn in #7827 -
Support
client.refetchQueriesas an imperative way to refetch queries, without having to passoptions.refetchQueriestoclient.mutate.
@dannycochran in #7431 -
Improve standalone
client.refetchQueriesmethod to support automatic detection of queries needing to be refetched.
@benjamn in #8000 -
Fix remaining barriers to loading
@apollo/client/coreas native ECMAScript modules from a CDN like esm.run. Importing@apollo/clientfrom a CDN will become possible once we move all React-related dependencies into@apollo/client/reactin Apollo Client 4.
@benjamn in #8266 -
InMemoryCachesupports a new method calledbatch, which is similar toperformTransactionbut takes named options rather than positional parameters. One of these named options is anonDirty(watch, diff)callback, which can be used to determine which watched queries were invalidated by thebatchoperation.
@benjamn in #7819 -
Allow
merge: truefield policy to mergeReferenceobjects with non-normalized objects, and vice-versa.
@benjamn in #7778 -
Allow identical subscriptions to be deduplicated by default, like queries.
@jkossis in #6910 -
Always use
POSTrequest when falling back to sending full query with@apollo/client/link/persisted-queries.
@rieset in #7456 -
The
FetchMoreQueryOptionstype now takes two instead of three type parameters (<TVariables, TData>), thanks to usingPartial<TVariables>instead ofK extends typeof TVariablesandPick<TVariables, K>.
@ArnaudBarre in #7476 -
Pass
variablesandcontextto a mutation'supdatefunction. Note: The type of theupdatefunction is now namedMutationUpdaterFunctionrather thanMutationUpdaterFn, since the older type was broken beyond repair. If you are usingMutationUpdaterFnin your own code, please useMutationUpdaterFunctioninstead.
@jcreighton in #7902 -
A
resultCacheMaxSizeoption may be passed to theInMemoryCacheconstructor to limit the number of result objects that will be retained in memory (to speed up repeated reads), and callingcache.reset()now releases all such memory.
@SofianHn in #8107 -
Fully remove result cache entries from LRU dependency system when the corresponding entities are removed from
InMemoryCacheby eviction, or by any other means.
@sofianhn and @benjamn in #8147 -
Add expected/received
variablestoNo more mocked responses...error messages generated byMockLink.
@markneub in #8340 -
The
InMemoryCacheversion of thecache.gcmethod now supports additional options for removing non-essential (recomputable) result caching data.
@benjamn in #8421 -
Suppress noisy
Missing cache result fields...warnings by default unlesssetLogVerbosity("debug")called.
@benjamn in #8489 -
Improve interaction between React hooks and React Fast Refresh in development.
@andreialecu in #7952
Potentially disruptive changes
-
To avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4 automatically clears any
ROOT_MUTATIONfields from the cache after each mutation finishes. If you need this information to remain in the cache, you can prevent the removal by passing thekeepRootFields: trueoption toclient.mutate.ROOT_MUTATIONresult data are also passed to the mutationupdatefunction, so we recommend obtaining the results that way, rather than usingkeepRootFields: true, if possible.
@benjamn in #8280 -
Internally, Apollo Client now controls the execution of development-only code using the
__DEV__global variable, rather thanprocess.env.NODE_ENV. While this change should not cause any visible differences in behavior, it will increase your minified+gzip bundle size by more than 3.5kB, unless you configure your minifier to replace__DEV__with atrueorfalseconstant, the same way you already replaceprocess.env.NODE_ENVwith a string literal like"development"or"production". For an example of configuring a Create React App project without ejecting, see this pull request for our React Apollo reproduction template.
@benjamn in #8347 -
Internally, Apollo Client now uses namespace syntax (e.g.
import * as React from "react") for imports whose types are re-exported (and thus may appear in.d.tsfiles). This change should remove any need to configureesModuleInteroporallowSyntheticDefaultImportsintsconfig.json, but might require updating bundler configurations that specify named exports of thereactandprop-typespackages, to include exports likecreateContextandcreateElement(example).
@devrelm in #7742 -
Respect
no-cachefetch policy (by not reading anydatafrom the cache) forloading: trueresults triggered bynotifyOnNetworkStatusChange: true.
@jcreighton in #7761 -
The TypeScript return types of the
getLastResultandgetLastErrormethods ofObservableQuerynow correctly include the possibility of returningundefined. If you happen to be calling either of these methods directly, you may need to adjust how the calling code handles the methods' possibly-undefinedresults.
@benjamn in #8394 -
Log non-fatal
invariant.errormessage when fields are missing from result objects written intoInMemoryCache, rather than throwing an exception. While this change relaxes an exception to be merely an error message, which is usually a backwards-compatible change, the error messages are logged in more cases now than the exception was previously thrown, and those new error messages may be worth investigating to discover potential problems in your application. The errors are not displayed for@client-only fields, so adding@clientis one way to handle/hide the errors for local-only fields. Another general strategy is to use a more precise query to write specific subsets of data into the cache, rather than reusing a larger query that contains fields not present in the writtendata.
@benjamn in #8416 -
The
nextFetchPolicyoption forclient.watchQueryanduseQuerywill no longer be removed from theoptionsobject after it has been applied, and instead will continue to be applied any timeoptions.fetchPolicyis reset to another value, until/unless theoptions.nextFetchPolicyproperty is removed fromoptions.
@benjamn in #8465 -
The
fetchMore,subscribeToMore, andupdateQueryfunctions returned from theuseQueryhook may now return undefined in edge cases where the functions are called when the component is unmounted
@noghartt in #7980.
Bug fixes
-
In Apollo Client 2.x, a
refetchoperation would always replace existing data in the cache. With the introduction of field policymergefunctions in Apollo Client 3, existing field values could be inappropriately combined with incoming field values by a custommergefunction that does not realize arefetchhas happened.To give you more control over this behavior, we have introduced an
overwrite?: boolean = falseoption forcache.writeQueryandcache.writeFragment, and an option calledrefetchWritePolicy?: "merge" | "overwrite"forclient.watchQuery,useQuery, and other functions that acceptWatchQueryOptions. You can use these options to make sure anymergefunctions involved in cache writes forrefetchoperations get invoked withundefinedas their first argument, which simulates the absence of any existing data, while still giving themergefunction a chance to determine the internal representation of the incoming data.The default behaviors are
overwrite: trueandrefetchWritePolicy: "overwrite", which restores the Apollo Client 2.x behavior, but (if this change causes any problems for your application) you can easily recover the previous merging behavior by setting a default value forrefetchWritePolicyindefaultOptions.watchQuery:new ApolloClient({ defaultOptions: { watchQuery: { refetchWritePolicy: "merge", }, }, }); -
Make sure the
MockedResponseResultFunctiontype is re-exported.
@hwillson in #8315 -
InMemoryCachenow coalescesEntityStoreupdates to guarantee only onestore.merge(id, fields)call peridper cache write.
@benjamn in #8372 -
Fix polling when used with
<React.StrictMode>.
@brainkim in #8414 -
Fix the React integration logging
Warning: Can't perform a React state update on an unmounted component.
@wuarmin in #7745 -
Make
ObservableQuery#getCurrentResultalways callqueryInfo.getDiff().
@benjamn in #8422 -
Make
readFielddefault to reading from current object only when thefromoption/argument is actually omitted, not whenfromis passed toreadFieldwith an undefined value. A warning will be printed when this situation occurs.
@benjamn in #8508 -
The
fetchMore,subscribeToMore, andupdateQueryfunctions no longer throwundefinederrors
@noghartt in #7980.
Apollo Client 3.3.21
Bug fixes
-
Fix race condition in
@apollo/client/link/contextthat could leak subscriptions if the subscription is cancelled beforeoperation.setContextis called.
@sofianhn in #8399 -
Prefer
existing.pageInfo.startCursorandendCursor(if defined) inreadfunction ofrelayStylePaginationpolicies.
@benjamn in #8438
Improvements
Apollo Client 3.3.20
Bug fixes
- Fix policy merging bug when calling
cache.policies.addTypePoliciesmultiple times for the same type policy.
@Banou26 in #8361
Apollo Client 3.3.19
Bug fixes
- Use
export ... fromsyntax to re-exportgraphql-tagnamed exports, making tree-shaking easier for some bundlers.
@benjamn in #8221
Documentation
- Replace Spectrum references with community.apollographql.com.
@hwillson in #8238
Apollo Client 3.3.18
Bug fixes
- Add
"sideEffects": falseto all generated/publishedpackage.jsonfiles, to improve dead code elimination for nested entry points like@apollo/client/cache.
@benjamn in #8213
Apollo Client 3.3.17
Bug fixes
- Make
useReactiveVar(rv)recheck the latestrv()value in itsuseEffectcallback, and immediately update state if the value has already changed, rather than callingrv.onNextChange(setValue)to listen for future changes.
@benjamn in #8135
Apollo Client 3.3.16
Bug fixes
-
Prevent
undefinedmutation result inuseMutation.
@jcreighton in #8018 -
Fix
useReactiveVarnot rerendering for successive synchronous calls.
@brainkim in #8022 -
Support
batchDebounceoption forBatchLinkandBatchHttpLink.
@dannycochran in #8024
Apollo Client 3.3.15
-
Increment
queryInfo.lastRequestIdonly when making a network request through theApolloLinkchain, rather than every timefetchQueryByPolicyis called.
@dannycochran in #7956 -
During server-side rendering, allow initial
useQuerycalls to return final{ loading: false, data }results when the cache already contains the necessary data.
@benjamn in #7983
Apollo Client 3.3.14
Improvements
- Adjust TypeScript types to allow
keyFieldsandkeyArgsfunctions to returnfalse.
@CarsonF and @benjamn in #7900
Bug fixes
-
Prevent
RenderPromisesmemory leak by callingrenderPromises.clear()aftergetMarkupFromTreefinishes.
@benjamn in #7943 -
Cancel pending notify timeout when stopping a
QueryInfoobject.
@hollandThomas in #7935 -
Fix infinite rendering bug related to
useSubscription.
@brainkim in #7917
Apollo Client 3.3.13
Improvements
-
Add missing
contextoption touseSubscription.
@jcreighton in #7860 -
Remove unnecessary TypeScript global
Observable<T>["@@observable"]method declaration.
@benjamn in #7888 -
Prevent skipped/observerless
ObservableQuerys from being refetched byrefetchQueries.
@dannycochran in #7877
Apollo Client 3.3.12
Bug fixes
-
Maintain serial ordering of
asyncMapmapping function calls, and prevent potential unhandledPromiserejection errors.
@benjamn in #7818 -
Relax incompatible
children?: React.ReactElementfield type inMockedProviderPropsinterface.
@kevinperaza in #7833
Apollo Client 3.3.11
Bug fixes
- Fix
useLazyQueryforceUpdateloop regression introduced by #7655 in version 3.3.10.
@benjamn in #7715
Apollo Client 3.3.10
Bug fixes
-
Revert PR #7276, but test that garbage collection reclaims torn-down
ObservableQueryobjects.
@benjamn in #7695 -
Reset
QueryInfo.diffandQueryInfo.dirtyafter canceling notify timeout inQueryInfo.markResultandQueryInfo.markError.
@jcreighton in #7696
Improvements
-
Avoid calling
forceUpdatewhen component is unmounted.
@DylanVann in #7655 -
The
codemods/top-level directory has been moved into thescripts/directory.
@benjamn in #7675
Apollo Client 3.3.9
Bug Fixes
- Prevent reactive variables from retaining otherwise unreachable
InMemoryCacheobjects.
@benjamn in #7661
Improvements
- The
graphql-tagdependency has been updated to version 2.12.0, after converting its repository to use TypeScript and ECMAScript module syntax. There should be no visible changes in behavior, though the internal changes seemed significant enough to mention here.
@abdonrd in graphql-tag#273 and @PowerKiKi in graphql-tag#325
Apollo Client 3.3.8
Bug Fixes
-
Catch updates in
useReactiveVarwith an additional check.
@jcreighton in #7652 -
Reactivate forgotten reactive variables whenever
InMemoryCacheacquires its first watcher.
@benjamn in #7657 -
Backport
Symbol.speciesfix forConcastandObservableQueryfromrelease-3.4, fixing subscriptions in React Native Android when the Hermes JavaScript engine is enabled (among other benefits).
@benjamn in #7403 and #7660
Apollo Client 3.3.7
Bug Fixes
-
Fix a regression due to #7310 that caused
loadingalways to betrueforskip: trueresults during server-side rendering.
@rgrove in #7567 -
Avoid duplicate
useReactiveVarlisteners when rendering inReact.StrictMode.
@jcreighton in #7581
Improvements
- Set
displayNameonApolloContextobjects for easier debugging.
@dulmandakh in #7550
Apollo Client 3.3.6
Bug Fixes
-
Immediately apply
queryType: true,mutationType: true, andsubscriptionType: truetype policies, rather than waiting for the first time the policy is used, fixing a regression introduced by #7065.
@benjamn in #7463 -
Check that
windowis defined even whenconnectToDevToolsistrue.
@yasupeke in #7434
Improvements
-
Replace stray
console.debug(undefined in React Native) withinvariant.log.
@benjamn in #7454 -
Suggest Firefox Apollo DevTools as well as the Chrome extension.
@benjamn in #7461
Apollo Client 3.3.5
Improvements
- Restore
client.versionproperty, reflecting the current@apollo/clientversion frompackage.json.
@benjamn in #7448
Apollo Client 3.3.4
Improvements
- Update
ts-invariantto avoid potential Content Security Policy-violatingFunctionfallback, thanks to a clever newglobalThispolyfill technique.
@benjamn in #7414
Apollo Client 3.3.3
Bug fixes
- Make the
observerparameter ofApolloLink#onErroroptional, fixing an unnecessary breaking change for any code that calledonErrordirectly.
@benjamn in #7407
Apollo Client 3.3.2
⚠️ Note: This version of
@apollo/clientcontains no behavioral changes since version 3.3.1
Documentation
-
The Pagination article has been completely rewritten (and split into multiple pages) to cover Apollo Client 3 field policies.
@benjamn and @StephenBarlow in #7175 -
Revamp local state tutorial chapter for Apollo Client 3, including reactive variables.
@StephenBarlow inapollographql@apollo#1050 -
Add examples of using
ApolloLinkto modify response data asynchronously.
@alichry in #7332 -
Consolidate separate v2.4, v2.5, and v2.6 documentation versions into one v2 version.
@jgarrow in #7378
Apollo Client 3.3.1
Bug Fixes
- Revert back to
default-importingReactinternally, rather than using a namespace import.
@benjamn in 113475b1
Apollo Client 3.3.0
Bug Fixes
-
Update
@wry/equalityto consider undefined properties equivalent to missing properties.
@benjamn in #7108 -
Prevent memory leaks involving unused
onBroadcastfunction closure created inApolloClientconstructor.
@kamilkisiela in #7161 -
Provide default empty cache object for root IDs like
ROOT_QUERY, to avoid differences in behavior before/afterROOT_QUERYdata has been written intoInMemoryCache.
@benjamn in #7100 -
Cancel
queryInfo.notifyTimeoutinQueryInfo#markResultto prevent unnecessary network requests when using aFetchPolicyofcache-and-networkornetwork-onlyin a React component with multipleuseQuerycalls.
@benjamn in #7347
Potentially breaking changes
-
Ensure
cache.readQueryandcache.readFragmentalways returnTData | null, instead of throwingMissingFieldErrorexceptions when missing fields are encountered.
@benjamn in #7098Since this change converts prior exceptions to
nullreturns, and sincenullwas already a possible return value according to theTData | nullreturn type, we are confident this change will be backwards compatible (as long asnullwas properly handled before). -
HttpLinkwill now automatically strip any unusedvariablesbefore sending queries to the GraphQL server, since those queries are very likely to fail validation, according to the All Variables Used rule in the GraphQL specification. If you depend on the preservation of unused variables, you can restore the previous behavior by passingincludeUnusedVariables: trueto theHttpLinkconstructor (which is typically passed asoptions.linkto theApolloClientconstructor).
@benjamn in #7127 -
Ensure
MockLink(used byMockedProvider) returns mock configuration errors (e.g.No more mocked responses for the query ...) through the Link'sObservable, instead of throwing them. These errors are now available through theerrorproperty of a result.
@hwillson in #7110Returning mock configuration errors through the Link's
Observablewas the default behavior in Apollo Client 2.x. We changed it for 3, but the change has been problematic for those looking to migrate from 2.x to 3. We've decided to change this back with the understanding that not many people want or are relying onMockLink's throwing exception approach. If you want to change this functionality, you can define custom error handling throughMockLink.setOnError. -
Unsubscribing the last observer from an
ObservableQuerywill once again unsubscribe from the underlying networkObservablein all cases, as in Apollo Client 2.x, allowing network requests to be cancelled by unsubscribing.
@javier-garcia-meteologica in #7165 and #7170. -
The independent
QueryBaseOptionsandModifiableWatchQueryOptionsinterface supertypes have been eliminated, and their fields are now defined byQueryOptions.
@DCtheTall in #7136 -
Internally, Apollo Client now avoids nested imports from the
graphqlpackage, importing everything from the top-level package instead. For example,import { visit } from "graphql/language/visitor";is now just
import { visit } from "graphql";Since the
graphqlpackage uses.mjsmodules, your bundler may need to be configured to recognize.mjsfiles as ECMAScript modules rather than CommonJS modules.
@benjamn in #7185
Improvements
-
Support inheritance of type and field policies, according to
possibleTypes.
@benjamn in #7065 -
Allow configuring custom
mergefunctions, including themerge: trueandmerge: falseshorthands, in type policies as well as field policies.
@benjamn in #7070 -
The verbosity of Apollo Client console messages can be globally adjusted using the
setLogVerbosityfunction:import { setLogVerbosity } from "@apollo/client"; setLogVerbosity("log"); // display all messages setLogVerbosity("warn"); // display only warnings and errors (default) setLogVerbosity("error"); // display only errors setLogVerbosity("silent"); // hide all console messagesRemember that all logs, warnings, and errors are hidden in production.
@benjamn in #7226 -
Modifying
InMemoryCachefields that havekeyArgsconfigured will now invalidate only the field value with matching key arguments, rather than invalidating all field values that share the same field name. IfkeyArgshas not been configured, the cache must err on the side of invalidating by field name, as before.
@benjamn in #7351 -
Shallow-merge
options.variableswhen combining existing or default options with newly-provided options, so new variables do not completely overwrite existing variables.
@amannn in #6927 -
Avoid displaying
Cache data may be lost...warnings for scalar field values that happen to be objects, such as JSON data.
@benjamn in #7075 -
In addition to the
result.dataproperty,useQueryanduseLazyQuerywill now provide aresult.previousDataproperty, which can be useful when a network request is pending andresult.datais undefined, sinceresult.previousDatacan be rendered instead of rendering an empty/loading state.
@hwillson in #7082 -
Passing
validate: trueto theSchemaLinkconstructor will enable validation of incoming queries against the local schema before execution, returning validation errors inresult.errors, just like a non-local GraphQL endpoint typically would.
@amannn in #7094 -
Allow optional arguments in
keyArgs: [...]arrays forInMemoryCachefield policies.
@benjamn in #7109 -
Avoid registering
QueryPromisewhenskipistrueduring server-side rendering.
@izumin5210 in #7310 -
ApolloCacheobjects (includingInMemoryCache) may now be associated with or disassociated from individual reactive variables by callingreactiveVar.attachCache(cache)and/orreactiveVar.forgetCache(cache).
@benjamn in #7350
Apollo Client 3.2.9
Bug Fixes
- Revert back to
default-importingReactinternally, rather than using a namespace import.
@benjamn in 113475b1
Apollo Client 3.2.8
Bug Fixes
-
Ensure
sourcesContentarray is properly defined in.js.mapfiles generated bytsc.
@benjamn in #7371 -
Avoid relying on global
Symbolproperties inApolloContext.ts.
@benjamn in #7371
Apollo Client 3.2.7
Bug Fixes
- Revert updating
symbol-observablefrom version 2.x to version 3, which caused TypeScript errors with some@types/nodeversions, especially in Angular applications.
@benjamn in #7340
Apollo Client 3.2.6
Bug Fixes
-
Always consider singleton IDs like
ROOT_QUERYandROOT_MUTATIONto be root IDs duringcache.gcgarbage collection, regardless of whether they have been retained or released.
@benjamn in #7333 -
Use optional chaining syntax (
this.currentObservable?.refetch) in Reactrefetchwrapper function to avoid crashing when an unmounted component is accidentally refetched.
@tm1000 in #6314 and @linmic in #7186
Improvements
-
Handle older
react-apollopackage incodemods/ac2-to-ac3/imports.jsmigration script.
@tm1000 in #7216 -
Ensure
relayStylePaginationpreservespageInfo.{start,end}Cursorifedgesis missing or empty.
@beaucollins in #7224
Apollo Client 3.2.5
Improvements
-
Move
terserdependency fromdependenciestodevDependencies.
@SimenB in #7188 -
Avoid all sub-package imports from the
graphqlnpm package.
@stoically in #7185
Apollo Client 3.2.4
Improvements
-
Update the
optimismnpm dependency to version 0.13.0 in order to use the newoptimistic.forgetmethod to fix a potentialcache.watchmemory leak.
@benjamn in #7157 -
Consider
cache.reseta destructive method, likecache.evictandcache.modify.
@joshjg in #7150 -
Avoid refetching observerless queries with
reFetchObservableQueries.
@joshjg in #7146
Apollo Client 3.2.3
Improvements
Apollo Client 3.2.2
Bug Fixes
- Undo
TEdgeWrapperapproach forrelayStylePagination, introduced by f41e9efc in #7023, since it was an unintended breaking change for existing code that usedcache.modifyto interact with field data managed byrelayStylePagination.
@benjamn in #7103
Apollo Client 3.2.1
Bug Fixes
-
Fix
relayStylePaginationto handle the possibility that edges might be normalizedReferenceobjects (uncommon).
@anark and @benjamn in #7023 -
Disable "Missing cache result fields" warnings when
returnPartialDataistrue.
@hwillson in #7055
Improvements
- Mark
subscriptions-transport-wspeerDependencyas optional.
@MasterOdin in #7047
Apollo Client 3.2.0
Bug Fixes
-
Use
options.nextFetchPolicyinternally to restore originalFetchPolicyafter polling withfetchPolicy: "network-only", so that polling does not interfere with normal query watching.
@benjamn in #6893 -
Initialize
ObservableQueryinupdateObservableQueryeven ifskipistrue.
@mu29 in #6999 -
Prevent full reobservation of queries affected by optimistic mutation updates, while still delivering results from the cache.
@benjamn in #6854
Improvements
-
In TypeScript, all APIs that take
DocumentNodeparameters now may alternatively takeTypeDocumentNode<Data, Variables>. This type has the same JavaScript representation but allows the APIs to infer the data and variable types instead of requiring you to specify types explicitly at the call site.
@dotansimha in #6720 -
Bring back an improved form of heuristic fragment matching, by allowing
possibleTypesto specify subtype regular expression strings, which count as matches if the written result object has all the fields expected for the fragment.
@benjamn in #6901 -
Allow
options.nextFetchPolicyto be a function that takes the currentFetchPolicyand returns a new (or the same)FetchPolicy, makingnextFetchPolicymore suitable for global use indefaultOptions.watchQuery.
@benjamn in #6893 -
Implement
useReactiveVarhook for consuming reactive variables in React components.
@benjamn in #6867 -
Move
apollo-link-persisted-queriesimplementation to@apollo/client/link/persisted-queries. Try running our automated imports transform to handle this conversion, if you're usingapollo-link-persisted-queries.
@hwillson in #6837 -
Disable feud-stopping logic after any
cache.evictorcache.modifyoperation.
@benjamn in #6817 and #6898 -
Throw if
writeFragmentcannot identifyoptions.datawhen nooptions.idprovided.
@jcreighton in #6859 -
Provide
options.storageobject tocache.modifyfunctions, as provided toreadandmergefunctions.
@benjamn in #6991 -
Allow
cache.modifyfunctions to returndetails.INVALIDATE(similar todetails.DELETE) to invalidate the current field, causing affected queries to rerun, even if the field's value is unchanged.
@benjamn in #6991 -
Support non-default
ErrorPolicyvalues (that is,"ignore"and"all", in addition to the default value"none") for mutations and subscriptions, like we do for queries.
@benjamn in #7003 -
Remove invariant forbidding a
FetchPolicyofcache-onlyinObservableQuery#refetch.
@benjamn in ccb0a79a, fixing #6702
Apollo Client 3.1.5
Bug Fixes
Improvements
Apollo Client 3.1.4
Bug Fixes
-
Restrict root object identification to
ROOT_QUERY(the ID corresponding to the rootQueryobject), allowingMutationandSubscriptionas user-defined types.
@benjamn in #6914 -
Prevent crash when
pageInfoand emptyedgesare received byrelayStylePagination.
@fracmak in #6918
Apollo Client 3.1.3
Bug Fixes
- Consider only
result.data(rather than all properties ofresult) when settling cache feuds.
@danReynolds in #6777
Improvements
- Provide jscodeshift transform for automatically converting Apollo Client 2.x
importdeclarations to use Apollo Client 3.x packages. Instructions.
@dminkovsky and @jcreighton in #6486
Apollo Client 3.1.2
Bug Fixes
Improvements
Apollo Client 3.1.1
Bug Fixes
- Re-export cache types from
@apollo/client/core(and thus also@apollo/client), again.
@benjamn in #6725
Apollo Client 3.1.0
Bug Fixes
-
Rework interdependencies between
@apollo/client/*entry points, so that CommonJS and ESM modules are supported equally well, without any duplication of shared code.
@benjamn in #6656 and #6657 -
Tolerate
!==callback functions (likeonCompletedandonError) inuseQueryoptions, since those functions are almost always freshly evaluated each timeuseQueryis called.
@hwillson and @benjamn in #6588 -
Respect
context.queryDeduplicationif provided, and otherwise fall back toclient.deduplication(as before).
@igaloly in #6261 and @Kujawadl in #6526 -
Refactor
ObservableQuery#getCurrentResultto reenable immediate delivery of warm cache results. As part of this refactoring, theApolloCurrentQueryResulttype was eliminated in favor ofApolloQueryResult.
@benjamn in #6710 -
Avoid clobbering
defaultOptionswithundefinedvalues.
@benjamn in #6715
Improvements
-
Apollo Client will no longer modify
options.fetchPolicyunless you passoptions.nextFetchPolicyto request an explicit change inFetchPolicyafter the current request. Although this is technically a breaking change,options.nextFieldPolicymakes it easy to restore the old behavior (by passingcache-first).
@benjamn in #6712, reverting #6353 -
Errors of the form
Invariant Violation: 42thrown in production can now be looked up much more easily, by consulting the auto-generated@apollo/client/invariantErrorCodes.jsfile specific to your@apollo/clientversion.
@benjamn in #6665 -
Make the
clientfield of theMutationResulttype non-optional, since it is always provided.
@glasser in #6617 -
Allow passing an asynchronous
options.renderFunctiontogetMarkupFromTree.
@richardscarrott in #6576 -
Ergonomic improvements for
mergeandkeyArgsfunctions in cache field policies.
@benjamn in #6714
Apollo Client 3.0.2
Bug Fixes
- Avoid duplicating
graphql/execution/executedependency in CommonJS bundle for@apollo/client/link/schema, fixinginstanceoferrors reported in #6621 and #6614.
@benjamn in #6624
Apollo Client 3.0.1
Bug Fixes
-
Make sure
useQueryonCompletedis not fired whenskipistrue.
@hwillson in #6589 -
Revert changes to
peerDependenciesinpackage.json(#6594), which would have allowed using incompatible future versions ofgraphqland/orreactdue to overly-permissive>=version constraints.
@hwillson in #6605
Apollo Client 3.0.0
Improvements
⚠️ Note: As of 3.0.0, Apollo Client uses a new package name:
@apollo/client
ApolloClient
-
[BREAKING]
ApolloClientis now only available as a named export. The defaultApolloClientexport has been removed.
@hwillson in #5425 -
[BREAKING] The
queryManagerproperty ofApolloClientinstances is now marked asprivate, paving the way for a more aggressive redesign of its API. -
[BREAKING] Apollo Client will no longer deliver "stale" results to
ObservableQueryconsumers, but will instead log more helpful errors about which cache fields were missing.
@benjamn in #6058 -
[BREAKING]
ApolloError's thrown by Apollo Client no longer prefix error messages withGraphQL error:orNetwork error:. To differentiate between GraphQL/network errors, refer toApolloError's publicgraphQLErrorsandnetworkErrorproperties.
@lorensr in #3892 -
[BREAKING] Support for the
@livedirective has been removed, but might be restored in the future if a more thorough implementation is proposed.
@benjamn in #6221 -
[BREAKING] Apollo Client 2.x allowed
@clientfields to be passed into thelinkchain ifresolverswere not set in the constructor. This allowed@clientfields to be passed into Links likeapollo-link-state. Apollo Client 3 enforces that@clientfields are local only, meaning they are no longer passed into thelinkchain, under any circumstances.
@hwillson in #5982 -
[BREAKING?] Refactor
QueryManagerto make better use of observables and enforcefetchPolicymore reliably.
@benjamn in #6221 -
The
updateQueryfunction previously required byfetchMorehas been deprecated with a warning, and will be removed in the next major version of Apollo Client. Please consider using amergefunction to handle incoming data instead of relying onupdateQuery.
@benjamn in #6464- Helper functions for generating common pagination-related field policies may be imported from
@apollo/client/utilities. The most basic helper isconcatPagination, which emulates the concatenation behavior of typicalupdateQueryfunctions. A more sophisticated helper isoffsetLimitPagination, which implements offset/limit-based pagination. If you are consuming paginated data from a Relay-friendly API, userelayStylePagination. Feel free to use these helper functions as inspiration for your own field policies, and/or modify them to suit your needs.
@benjamn in #6465
- Helper functions for generating common pagination-related field policies may be imported from
-
Updated to work with
graphql@15.
@durchanek in #6194 and #6279
@hagmic in #6328 -
Apollo Link core and HTTP related functionality has been merged into
@apollo/client. Functionality that was previously available through theapollo-link,apollo-link-http-commonandapollo-link-httppackages is now directly available from@apollo/client(e.g.import { HttpLink } from '@apollo/client'). TheApolloClientconstructor has also been updated to accept newuri,headersandcredentialsoptions. Ifuriis specified, Apollo Client will take care of creating the necessaryHttpLinkbehind the scenes.
@hwillson in #5412 -
The
gqltemplate tag should now be imported from the@apollo/clientpackage, rather than thegraphql-tagpackage. Although thegraphql-tagpackage still works for now, future versions of@apollo/clientmay change the implementation details ofgqlwithout a major version bump.
@hwillson in #5451 -
@apollo/client/corecan be used to import the Apollo Client core, which includes everything the main@apollo/clientpackage does, except for all React related functionality.
@kamilkisiela in #5541 -
Several deprecated methods have been fully removed:
ApolloClient#initQueryManagerQueryManager#startQueryObservableQuery#currentResult
-
Apollo Client now supports setting a new
ApolloLink(or link chain) afternew ApolloClient()has been called, using theApolloClient#setLinkmethod.
@hwillson in #6193 -
The final time a mutation
updatefunction is called, it can no longer accidentally read optimistic data from other concurrent mutations, which ensures the use of optimistic updates has no lasting impact on the state of the cache after mutations have finished.
@benjamn in #6551 -
Apollo links that were previously maintained in https://github.com/apollographql/apollo-link have been merged into the Apollo Client project. They should be accessed using the new entry points listed in the migration guide.
@hwillson in #
InMemoryCache
⚠️ Note:
InMemoryCachehas been significantly redesigned and rewritten in Apollo Client 3.0. Please consult the migration guide and read the new documentation to understand everything that has been improved.
-
The
InMemoryCacheconstructor should now be imported directly from@apollo/client, rather than from a separate package. Theapollo-cache-inmemorypackage is no longer supported.The
@apollo/client/cacheentry point can be used to importInMemoryCachewithout importing other parts of the Apollo Client codebase.
> @hwillson in #5577 -
[BREAKING]
FragmentMatcher,HeuristicFragmentMatcher, andIntrospectionFragmentMatcherhave all been removed. We now recommend usingInMemoryCache’spossibleTypesoption instead. For more information see the DefiningpossibleTypesmanually section of the docs.
@benjamn in #5073 -
[BREAKING] As promised in the Apollo Client 2.6 blog post, all cache results are now frozen/immutable.
@benjamn in #5153 -
[BREAKING] Eliminate "generated" cache IDs to avoid normalizing objects with no meaningful ID, significantly reducing cache memory usage. This might be a backwards-incompatible change if your code depends on the precise internal representation of normalized data in the cache.
@benjamn in #5146 -
[BREAKING]
InMemoryCachewill no longer merge the fields of written objects unless the objects are known to have the same identity, and the values of fields with the same name will not be recursively merged unless a custommergefunction is defined by a field policy for that field, within a type policy associated with the__typenameof the parent object.
@benjamn in #5603 -
[BREAKING]
InMemoryCachenow throws when data with missing or undefined query fields is written into the cache, rather than just warning in development.
@benjamn in #6055 -
[BREAKING]
client|cache.writeDatahave been fully removed.writeDatausage is one of the easiest ways to turn faulty assumptions about how the cache represents data internally, into cache inconsistency and corruption.client|cache.writeQuery,client|cache.writeFragment, and/orcache.modifycan be used to update the cache.
@benjamn in #5923 -
InMemoryCachenow supports tracing garbage collection and eviction. Note that the signature of theevictmethod has been simplified in a potentially backwards-incompatible way.
@benjamn in #5310-
[beta-BREAKING] Please note that the
cache.evictmethod now requiresCache.EvictOptions, though it previously supported positional arguments as well.
@danReynolds in #6141 @benjamn in #6364 -
Removing an entity object using the
cache.evictmethod does not automatically remove dangling references to that entity elsewhere in the cache, but dangling references will be automatically filtered from lists whenever those lists are read from the cache. You can define a custom fieldreadfunction to customize this behavior. See #6412, #6425, and #6454 for further explanation.
-
-
Cache methods that would normally trigger a broadcast, like
cache.evict,cache.writeQuery, andcache.writeFragment, can now be called with a named options object, which supports abroadcast: booleanproperty that can be used to silence the broadcast, for situations where you want to update the cache multiple times without triggering a broadcast each time.
@benjamn in #6288 -
InMemoryCachenowconsole.warns in development whenever non-normalized data is dangerously overwritten, with helpful links to documentation about normalization and custommergefunctions.
@benjamn in #6372 -
The result caching system (introduced in #3394) now tracks dependencies at the field level, rather than at the level of whole entity objects, allowing the cache to return identical (
===) results much more often than before.
@benjamn in #5617 -
InMemoryCachenow has a method calledmodifywhich can be used to update the value of a specific field within a specific entity object:cache.modify({ id: cache.identify(post), fields: { comments(comments: Reference[], { readField }) { return comments.filter( (comment) => idToRemove !== readField("id", comment) ); }, }, });This API gracefully handles cases where multiple field values are associated with a single field name, and also removes the need for updating the cache by reading a query or fragment, modifying the result, and writing the modified result back into the cache. Behind the scenes, the
cache.evictmethod is now implemented in terms ofcache.modify.
@benjamn in #5909 and #6178 -
InMemoryCacheprovides a new API for storing client state that can be updated from anywhere:import { makeVar } from "@apollo/client"; const v = makeVar(123); console.log(v()); // 123 console.log(v(v() + 1)); // 124 console.log(v()); // 124 v("asdf"); // TS type errorThese variables are reactive in the sense that updating their values invalidates any previously cached query results that depended on the old values.
@benjamn in #5799, #5976, and #6512 -
Various cache read and write performance optimizations, cutting read and write times by more than 50% in larger benchmarks.
@benjamn in #5948 -
The
cache.readQueryandcache.writeQuerymethods now accept anoptions.idstring, which eliminates most use cases forcache.readFragmentandcache.writeFragment, and skips the implicit conversion of fragment documents to query documents performed bycache.{read,write}Fragment.
@benjamn in #5930 -
Support
cache.identify(entity)for easily computing entity ID strings.
@benjamn in #5642 -
Support eviction of specific entity fields using
cache.evict(id, fieldName).
@benjamn in #5643 -
Make
InMemoryCache#evictremove data from allEntityStorelayers.
@benjamn in #5773 -
Stop paying attention to
previousResultinInMemoryCache.
@benjamn in #5644 -
Improve optimistic update performance by limiting cache key diversity.
@benjamn in #5648 -
Custom field
readfunctions can read from neighboring fields using thereadField(fieldName)helper, and may also read fields from other entities by callingreadField(fieldName, objectOrReference).
@benjamn in #5651 -
Expose cache
modifyandidentifyto the mutateupdatefunction.
@hwillson in #5956 -
Add a default
gcimplementation toApolloCache.
@justinwaite in #5974
React
-
[BREAKING] The
QueryOptions,MutationOptions, andSubscriptionOptionsReact Apollo interfaces have been renamed toQueryDataOptions,MutationDataOptions, andSubscriptionDataOptions(to avoid conflicting with similarly named and exported Apollo Client interfaces). -
[BREAKING] Results with
loading: truewill no longer redeliver previous data, though they may provide partial data from the cache, when available.
@benjamn in #6566 -
[BREAKING?] Remove
fixPolyfills.ts, except when bundling for React Native. If you have trouble withMaporSetoperations due to frozen key objects in React Native, either update React Native to version 0.59.0 (or 0.61.x, if possible) or investigate whyfixPolyfills.native.jsis not included in your bundle.
@benjamn in #5962 -
The contents of the
@apollo/react-hookspackage have been merged into@apollo/client, enabling the following all-in-oneimport:import { ApolloClient, ApolloProvider, useQuery } from "@apollo/client"; -
React SSR features (previously accessed via
@apollo/react-ssr) can now be accessed from the separate Apollo Client entry point of@apollo/client/react/ssr. These features are not included in the default@apollo/clientbundle.
@hwillson in #6499
General
-
[BREAKING] Removed
graphql-anywheresince it's no longer used by Apollo Client.
@hwillson in #5159 -
[BREAKING] Removed
apollo-boostsince Apollo Client 3.0 provides a boost like getting started experience out of the box.
@hwillson in #5217 -
[BREAKING] We are no longer exporting certain (intended to be) internal utilities. If you are depending on some of the lesser known exports from
apollo-cache,apollo-cache-inmemory, orapollo-utilities, they may no longer be available from@apollo/client.
@hwillson in #5437 and #5514Utilities that were previously externally available through the
apollo-utilitiespackage are now only available by importing from@apollo/client/utilities.
> @hwillson in #5683 -
Make sure all
graphql-tagpublic exports are re-exported.
@hwillson in #5861 -
Fully removed
prettier. The Apollo Client team has decided to no longer automatically enforce code formatting across the codebase. In most cases existing code styles should be followed as much as possible, but this is not a hard and fast rule.
@hwillson in #5227 -
Make sure
ApolloContextplays nicely with IE11 when storing the shared context.
@ms in #5840 -
Migrated React Apollo HOC and Components functionality into Apollo Client, making it accessible from
@apollo/client/react/componentsand@apollo/client/react/hocentry points.
@hwillson in #6558 -
Support passing a
contextobject through the link execution chain when using subscriptions.
@sgtpepper43 in #4925 -
MockSubscriptionLinknow supports multiple subscriptions.
@dfrankland in #6081
Bug Fixes
-
useMutationadjustments to help avoid an infinite loop / too many renders issue, caused by unintentionally modifying theuseStatebased mutation result directly.
@hwillson in #5770 -
Missing
__typenamefields no longer cause theInMemoryCache#diffresult to be markedcomplete: false, if those fields were added byInMemoryCache#transformDocument(which callsaddTypenameToDocument).
@benjamn in #5787 -
Fixed an issue that allowed
@client @exportbased queries to lead to extra unnecessary network requests being fired.
@hwillson in #5946 -
Refined
useLazyQuerytypes to help prevent runtime errors.
@benmosher in #5935 -
Make sure
@client @exportvariables used in watched queries are updated each time the query receives new data that changes the value of the@exportvariable.
@hwillson in #5986 -
Ensure
useMutationpasses a definederrorPolicyoption into its underlyingApolloClient.mutate()call.
@jamesreggio in #5863 -
useQuery: Prevent new data re-render attempts during an existing render. This helps avoid React 16.13.0's "Cannot update a component from inside the function body of a different component" warning (https://github.com/facebook/react/pull/17099).
@hwillson in #6107 -
Expand
ApolloErrortypings to includeServerErrorandServerParseError.
@dmarkow in #6319 -
Fast responses received over the link chain will no longer conflict with
skipsettings.
@hwillson in #6587
Apollo Client 2.6.8
Apollo Client (2.6.8)
-
Update the
fetchMoretype signature to acceptcontext.
@koenpunt in #5147 -
Fix type for
Resolverand use it in the definition ofResolvers.
@peoplenarthax in #4943 -
Local state resolver functions now receive a
fragmentMap: FragmentMapobject, in addition to thefield: FieldNodeobject, via theinfoparameter.
@mjlyons in #5388 -
Documentation updates.
@tomquirk in #5645
@Sequoia in #5641
@phryneas in #5628
@AryanJ-NYC in #5560
GraphQL Anywhere (4.2.6)
- Fix
filteredge case involvingnull.
@lifeiscontent in #5110
Apollo Boost (0.4.7)
-
Replace
GlobalFetchreference withWindowOrWorkerGlobalScope.
@abdonrd in #5373 -
Add
assumeImmutableResultstyping to apollo boostPresetConfiginterface.
@bencoullie in #5571
Apollo Client (2.6.4)
Apollo Client (2.6.4)
-
Modify
ObservableQueryto allow queries withnotifyOnNetworkStatusChangeto be notified when loading after an error occurs.
@jasonpaulos in #4992 -
Add
graphqlas apeerDependencyofapollo-cacheandgraphql-anywhere.
@ssalbdivad in #5081
Apollo Client (2.6.3)
Apollo Client (2.6.3)
- A new
ObservableQuery.resetQueryStoreErrors()method is now available that can be used to clear outObservableQueryquery store errors.
@hwillson in #4941 - Documentation updates.
@michael-watson in #4940
@hwillson in #4969
Apollo Client (2.6.1)
Apollo Utilities 1.3.2
Apollo Client (2.6.1)
- In all Apollo Client packages, the compilation of
lib/bundle.esm.jstolib/bundle.cjs.jsandlib/bundle.umd.jsnow uses Babel instead of Rollup, since Babel correctly compiles some edge cases that neither Rollup nor TypeScript compile correctly.
@benjamn in #4911
Apollo Cache In-Memory 1.6.1
Apollo Utilities 1.3.1
- The
isEqualfunction has been reimplemented using thelodash.isequalnpm package, to better support circular references. Since thelodash.isequalpackage is already used byreact-apollo, this change is likely to decrease total bundle size.
@capaj in #4915
Apollo Client (2.6.0)
- In production,
invariant(condition, message)failures will now include a unique error code that can be used to trace the error back to the point of failure.
@benjamn in #4521
Apollo Client 2.6.0
-
If you can be sure your application code does not modify cache result objects (see
freezeResultsnote below), you can unlock substantial performance improvements by communicating this assumption vianew ApolloClient({ assumeImmutableResults: true });which allows the client to avoid taking defensive snapshots of past results using
cloneDeep, as explained by @benjamn in #4543. -
Identical overlapping queries are now deduplicated internally by
apollo-client, rather than using theapollo-link-deduppackage.
@benjamn in commit 7cd8479f -
The
FetchPolicytype has been split into two types, so that passingcache-and-networktoApolloClient#queryis now forbidden at the type level, whereas previously it was forbidden by a runtimeinvariantassertion:export type FetchPolicy = | "cache-first" | "network-only" | "cache-only" | "no-cache" | "standby"; export type WatchQueryFetchPolicy = FetchPolicy | "cache-and-network";The exception thrown if you ignore the type error has also been improved to explain the motivation behind this restriction.
Issue #3130 (comment) and commit cf069bc7 -
Avoid updating (and later invalidating) cache watches when
fetchPolicyis'no-cache'.
@bradleyayers in PR #4573, part of issue #3452 -
Remove temporary
queryIdafterfetchMorecompletes.
@doomsower in #4440 -
Call
clearStorecallbacks after clearing store.
@ds8k in #4695 -
Perform all
DocumentNodetransforms once, and cache the results.
@benjamn in #4601 -
Accommodate
@client @exportvariable changes inObservableQuery.
@hwillson in #4604 -
Support the
returnPartialDataoption for watched queries again.
@benjamn in #4743 -
Preserve
networkStatusfor incompletecache-and-networkqueries.
@benjamn in #4765 -
Preserve
cache-and-networkfetchPolicywhen refetching.
@benjamn in #4840 -
Update the React Native docs to remove the request for external example apps that we can link to. We're no longer going to manage a list of external example apps.
@hwillson in #4531 -
Polling queries are no longer batched together, so their scheduling should be more predictable.
@benjamn in #4800
Apollo Cache In-Memory 1.6.0
-
Support
new InMemoryCache({ freezeResults: true })to help enforce immutability.
@benjamn in #4514 -
Allow
IntrospectionFragmentMatcherto match fragments against the rootQuery, asHeuristicFragmentMatcherdoes.
@rynobax in #4620 -
Rerential identity (
===) of arrays in cache results will now be preserved for unchanged data.
@benjamn in commit f3091d6a -
Avoid adding
__typenamefield to@clientselection sets that have been@exported as input variables.
@benjamn in #4784
GraphQL Anywhere 4.2.2
- The
graphqlfunction can now be configured to ignore@includeand@skipdirectives (useful when walking a fragment to generate prop types or filter result data).
@GreenGremlin in #4373
Apollo Client 2.5.1
apollo-client 2.5.1
graphql-anywhere 4.2.1
Apollo Client (2.5.0)
Apollo Client (2.5.0)
- Introduces new local state management features (client-side schema
and local resolver /
@clientsupport) and many overall code improvements, to help reduce the Apollo Client bundle size.
#4361 - Revamped CJS and ESM bundling approach with Rollup.
@rosskevin in #4261 - Fixes an issue where the
QueryManagerwas accidentally returning cached data fornetwork-onlyqueries.
@danilobuerger in #4352 - Fixed an issue in the repo
.gitattributesthat was causing binary files to have their line endings adjusted, and cleaned up corrupted documentation images (ref: https://github.com/apollographql/apollo-client/pull/4232).
@rajington in #4438 - Improve (and shorten) query polling implementation.
PR #4337
Apollo Client (2.4.13)
Apollo Client (2.4.13)
-
Resolve "invalidate" -> "invalidated" typo in
QueryManager.
@quazzie in #4041 -
Properly type
setQueryand fix now typed callers.
@danilobuerger in #4369 -
Align with the React Apollo decision that result
datashould beTData | undefinedinstead ofTData | {}.
@danilobuerger in #4356 -
Documentation updates.
@danilobuerger in #4340
@justyn-clark in #4383
@jtassin in #4287
@Gongreg in #4386
@davecardwell in #4399
@michaelknoch in #4384
Apollo Client (2.4.12)
Apollo Client (2.4.12)
- Support
ApolloClient#stopmethod for safe client disposal.
PR #4336
Apollo Client (2.4.11)
- Added explicit dependencies on the
tslibpackage to all client packages to fix Issue #4332.
Apollo Client (2.4.11)
- Reverted some breaking changes accidentally released in a patch version (2.4.10). PR #4334
Apollo Client (2.4.10)
Apollo Client (2.4.10)
-
The
apollo-clientpackage no longer exports aprintASTfunction fromgraphql/language/printer. If you need this functionality, import it directly:import { print } from "graphql/language/printer" -
Query polling now uses a simpler scheduling strategy based on a single
setTimeoutinterval rather than multiplesetIntervaltimers. The new timer fires at the rate of the fastest polling interval, and queries with longer polling intervals fire whenever the time elapsed since they last fired exceeds their desired interval.
PR #4243
Apollo Cache In-Memory (1.4.1)
-
The
optimismnpm package has been updated to a version (0.6.9) that provides its own TypeScript declarations, which should fix problems like Issue #4327.
PR #4331 -
Error messages involving GraphQL queries now print the queries using
JSON.stringifyinstead of theprintfunction exported by thegraphqlpackage, to avoid pulling unnecessary printing logic into your JavaScript bundle.
PR #4234 -
The
QueryKeyMakerabstraction has been removed, meaning that cache results for non-identical queries (or sub-queries) with equivalent structure will no longer be cached together. This feature was a nice optimization in certain specific use cases, but it was not worth the additional complexity or bundle size.
PR #4245
Apollo Utilities (1.1.1)
-
The
flattenSelectionshelper function is no longer exported fromapollo-utilities, sincegetDirectiveNameshas been reimplemented without usingflattenSelections, andflattenSelectionshas no clear purpose now. If you need the old functionality, use a visitor:import { visit } from "graphql/language/visitor"; function flattenSelections(selection: SelectionNode) { const selections: SelectionNode[] = []; visit(selection, { SelectionSet(ss) { selections.push(...ss.selections); }, }); return selections; }
Apollo Client (2.4.9)
Apollo Client (2.4.9)
-
Apollo Client has been updated to use
graphql14.x as a dev dependency.
@hwillson in #4233 -
The
onClearStorefunction can now be used to register callbacks that should be triggered when callingclearStore.
@joe-re in #4082 -
Make
isApolloErroravailable for external use.
@FredyC in #4223 -
The
QueryManagernow callscompleteon the observables used by Apollo Client's Subscription handling. This gives finite subscriptions a chance to handle cleanup.
@sujeetsr in #4290 -
Documentation updates.
@lifedup in #3931
@Dem0n3D in #4008
@anand-sundaram-zocdoc in #4009
@mattphoto in #4026
@birge in #4029
@mxstbr in #4127
@Caerbannog in #4140
@jedwards1211 in #4179
@nutboltu in #4182
@CarloPalinckx in #4189
@joebernard in #4206
@evans in #4213
@danilobuerger in #4214
@stubailo in #4220
@haysclark in #4255
@shelmire in #4266
@peggyrayzis in #4280
@caydie-tran in #4300
Apollo Utilities (1.1.0)
- Transformation utilities have been refactored to work with
graphql14.x. GraphQL AST's are no longer being directly modified.
@hwillson in #4233
Apollo Cache In-Memory (1.4.0)
-
The speed and memory usage of optimistic reads and writes has been improved dramatically using a new layering technique that does not require copying the non-optimistic contents of the cache.
PR #4319 -
The
RecordingCacheabstraction has been removed, and thus is no longer exported fromapollo-cache-inmemory.
PR #4319 -
Export the optimism
wrapfunction using ES2015 export syntax, instead of CommonJS.
@ardatan in #4158
Apollo Client (2.4.8)
Apollo Client (2.4.8)
-
Documentation and config updates.
@justinanastos in #4187
@PowerKiKi in #3693
@nandito in #3865 -
Schema/AST tranformation utilities have been updated to work properly with
@clientdirectives.
@justinmakaila in #3482
Apollo Cache In-Memory (1.3.12)
-
Avoid using
DepTrackingCachefor optimistic reads. PR #4521 -
When creating an
InMemoryCacheobject, it's now possible to disable the result caching behavior introduced in #3394, either for diagnostic purposes or because the benefit of caching repeated reads is not worth the extra memory usage in your application:new InMemoryCache({ resultCaching: false, });Part of PR #4521.
Apollo Client (2.4.7)
Apollo Client (2.4.7)
- The
ApolloClientconstructor has been updated to acceptnameandversionparams, that can be used to support Apollo Server Client Awareness functionality. These client awareness properties are passed into the defined Apollo Link chain, and are then ultimately sent out as custom headers with outgoing requests.
@hwillson in #4154
Apollo Boost (0.1.22)
- No changes.
Apollo Cache (1.1.21)
- No changes.
Apollo Cache In-Memory (1.3.11)
- No changes.
Apollo Utilities (1.0.26)
- No changes.
Graphql Anywhere (4.1.23)
- No changes.
Apollo Client (2.4.6)
Apollo Cache In-Memory (1.3.10)
-
Added some
returns to prevent errors withnoImplicitReturnsTypeScript rule. PR #4137 -
Exclude the
src/directory when publishingapollo-cache-inmemory. Issue #4083
Apollo Client (2.4.5)
-
Optimistic tests cleanup. PR #3834 by @joshribakoff
-
Documentation updates. PR #3840 by @chentsulin and PR #3844 by @lorensr
-
Implement
ObservableQuery#isDifferentFromLastResultto fix Issue #4054 and Issue #4031. PR #4069
Apollo Cache (1.1.20)
- Add
readQuerytest to make sure options aren't mutated. @CarloPalinckx in #3838
Apollo Cache In-Memory (1.3.9)
- Avoid modifying source objects when merging cache results. Issue #4081 PR #4089
Apollo Utilities (1.0.25)
Apollo Client (2.4.4)
Apollo Utilities (1.0.24)
-
Discard property accessor functions in
cloneDeephelper, to fix issue #4034. -
Unconditionally remove
cloneDeepproperty accessors. PR #4039 -
Avoid copying non-enumerable and/or
Symbolkeys incloneDeep. PR #4052
Apollo Cache In-Memory (1.3.7)
-
Throw when querying non-scalar objects without a selection set. Issue #4025 PR #4038
-
Work around spec non-compliance of
Map#setandSet#addin IE11. Issue #4024 PR #4012
Apollo Client (2.4.3)
-
Add additional checks to make sure we don't try to set the network status of queries in the store, when the store doesn't exist.
@i6mi6 in #3914 -
Documentation updates.
@shanonvl in #3925
@ojh102 in #3920
@Bkucera in #3919
@j4chou in #3915
@billfienberg in #3886
@TLadd in #3884 -
The
ObservableQueryclass now makes a deep clone oflastResultwhen first received, so that theisDifferentResultlogic will not be confused if the result object is modified later. Issue #3992 PR #4032
Apollo Cache In-Memory (1.3.6)
-
Optimize repeated
apollo-cache-inmemoryreads by caching partial query results, for substantial performance improvements. As a consequence, watched queries will not be rebroadcast unless the data have changed. PR #3394 -
Include root ID and fragment matcher function in cache keys computed by
StoreReader#executeStoreQueryandexecuteSelectionSet, and work around bugs in the React NativeMapandSetpolyfills. PR #3964 React Native PR #21492 (pending) -
The
apollo-cache-inmemorypackage now allowsgraphql@^14.0.0as a peer dependency. Issue #3978 -
The
apollo-cache-inmemorypackage now correctly broadcasts changes even when the new data is===to the old data, since the contents of the data object may have changed. Issue #3992 PR #4032
Apollo GraphQL Anywhere (4.1.20)
- Make
graphql-anywherefilterfunction generic (typescript).
@minznerjosh in #3929
Apollo Utilities (1.0.22)
- The
fclonepackage has been replaced with a customcloneDeepimplementation that is tolerant of cycles, symbol properties, and non-enumerable properties. PR #4032
Apollo Boost (0.1.17)
- Remove duplicate InMemoryCache export for Babel 6 compatibility. Issue #3910 PR #3932
Apollo Cache (1.1.18)
- No changes.
Apollo Client (2.4.2)
Apollo Client (2.4.2)
- Apollo Client no longer deep freezes query results. @hwillson in #3883
- A new
clearStoremethod has been added, that will remove all data from the store. UnlikeresetStore, it will not refetch active queries after removing store data. @hwillson in #3885
Apollo Utilities (1.0.21)
- Replace the custom
cloneDeepimplementation withfclone, to avoid crashing when encountering circular references.
@hwillson in #3881
Apollo Boost (0.1.16)
- No changes.
Apollo Cache (1.1.17)
- No changes.
Apollo Cache In-Memory (1.2.10)
- No changes.
Apollo GraphQL Anywhere (4.1.19)
- No changes.
2.4.1 (August 26, 2018)
Apollo Client (2.4.1)
-
mutate'srefetchQueriesoption now allows queries to include a customcontextoption. Thiscontextwill be used when refetching the query. For example:context = { headers: { token: 'some auth token', }, }; client.mutate({ mutation: UPDATE_CUSTOMER_MUTATION, variables: { userId: user.id, firstName, ... }, refetchQueries: [{ query: CUSTOMER_MESSAGES_QUERY, variables: { userId: user.id }, context, }], context, });The
CUSTOMER_MESSAGES_QUERYabove will be refetched usingcontext. Normally queries are refetched using the original context they were first started with, but this provides a way to override the context, if needed.
@hwillson in #3852
Apollo Boost (0.1.15)
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
Apollo Cache (1.1.16)
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
Apollo Cache In-Memory (1.2.9)
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
Apollo Utilities (1.0.20)
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
Apollo GraphQL Anywhere (4.1.18)
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
2.4.0 (August 17, 2018)
Apollo Client (2.4.0)
- Add proper error handling for subscriptions. If you have defined an
errorhandler on your subscription observer, it will now be called when an error comes back in a result, and thenexthandler will be skipped (similar to how we're handling errors with mutations). Previously, the error was just passed in the result to thenexthandler. If you don't have anerrorhandler defined, the previous functionality is maintained, meaning the error is passed in the result, giving the next handler a chance to deal with it. This should help address backwards compatibility (and is the reason for the minor version bumo in this release).
@clayne11 in #3800 - Allow an
optimisticparam to be passed intoApolloClient.readQueryandApolloClient.readFragment, that when set totrue, will allow optimistic results to be returned. Isfalseby default.
@jay1337 in #2429 - Optimistic tests cleanup.
@joshribakoff in #3713 - Make sure each package has its own
.npmignore, so they're taken into consideration when publishing via lerna.
@hwillson in #3828 - Documentation updates.
@toolness in #3804
@pungggi in #3798
@lorensr in #3748
@joshribakoff in #3730
@yalamber in #3819
@pschreibs85 in #3812
@msreekm in #3808
@kamaltmo in #3806
@lorensr in #3739
@brainkim in #3680
Apollo Cache In-Memory (1.2.8)
Apollo Boost (0.1.14)
- No changes.
Apollo Cache (1.1.15)
- No changes.
Apollo Utilities (1.0.19)
- No changes.
Apollo GraphQL Anywhere (4.1.17)
- No changes.
2.3.8 (August 9, 2018)
Apollo Client (2.3.8)
- Adjusted the
graphqlpeer dependency to cover explicit minor ranges. Since the ^ operator only covers any minor version if the major version is not 0 (since a major version of 0 is technically considered development by semver 2), the current ^0.11.0 || ^14.0.0 graphql range doesn't cover 0.12._ or 0.13._. This fixes theapollo-client@X has incorrect peer dependency "graphql@^0.11.0 || ^14.0.0"errors that people might have seen usinggraphql0.12.x or 0.13.x.
@hwillson in #3746 - Document
setVariablesinternal API status.
@PowerKiKi in #3692 - Corrected
ApolloClient.queryManagertyping as it may beundefined.
@danilobuerger in #3661 - Make sure using a
no-cachefetch policy with subscriptions prevents data from being cached.
@hwillson in #3773 - Fixed an issue that sometimes caused empty query results, when using the
no-cachefetch policy.
@hwillson in #3777 - Documentation updates.
@hwillson in #3750
@hwillson in #3754
@TheMightyPenguin in #3725
@bennypowers in #3668
@hwillson in #3762
@chentsulin in #3688
@chentsulin in #3687
@ardouglass in #3645
@hwillson in #3764
@hwillson in #3767
@hwillson in #3774
@hwillson in #3779
Apollo Boost (0.1.13)
- No changes.
Apollo Cache In-Memory (1.2.7)
- No changes.
Apollo Cache (1.1.14)
- No changes.
Apollo Utilities (1.0.18)
- No changes.
Apollo GraphQL Anywhere (4.1.16)
- No changes.
2.3.7 (July 24, 2018)
Apollo Client (2.3.7)
- Release 2.3.6 broke Typescript compilation.
QueryManager'sgetQueryWithPreviousResultmethod included an invalidvariablesreturn type in the auto-generatedcore/QueryManager.d.tsdeclaration file. The type definition had a locally referenced path, that appears to have been caused by the typescript compiler getting confused at compile/publish time.getQueryWithPreviousResultreturn types are now excplicity identified, which helps Typescript avoid the local type reference. For more details, see https://github.com/apollographql/apollo-client/issues/3729.
@hwillson in #3731
Apollo Boost (0.1.12)
- No changes.
2.3.6 (July 24, 2018)
Apollo Client (2.3.6)
- Documentation updates.
@ananth99 in #3599
@hwillson in #3635
@JakeDawkins in #3642
@hwillson in #3644
@gbau in #3644
@chentsulin in #3608
@MikaelCarpenter in #3609
@Gamezpedia in #3612
@jinxac in #3647
@abernix in #3705
@dandv in #3703
@hwillson in #3580 - Updated
graphqlpeerDependenciesto handle 14.x versions.
@ivank in #3598 - Add optional generic type params for variables on low level methods.
@mvestergaard in #3588 - Add a new
awaitRefetchQueriesconfig option to the Apollo Clientmutatefunction, that when set totruewill wait for allrefetchQueriesto be fully refetched, before resolving the mutation call.awaitRefetchQueriesisfalseby default.
@jzimmek in #3169
Apollo Boost (0.1.11)
- Allow
fetchto be given as a configuration option toApolloBoost.
@mbaranovski in #3590 - The
apollo-boostApolloClientconstructor now warns about unsupported options.
@quentin- in #3551
Apollo Cache (1.1.13)
- No changes.
Apollo Cache In-Memory (1.2.6)
- Add
__typenameandidproperties todataIdFromObjectparameter (typescript)
@jfurler in #3641 - Fixed an issue caused by
dataIdFromObjectconsidering returned 0 values to be falsy, instead of being a valid ID, which lead to the store not being updated properly in some cases.
@hwillson in #3711
Apollo Utilities (1.0.17)
- No changes.
Apollo GraphQL Anywhere (4.1.15)
- Add support for arrays to
graphql-anywhere's filter utility.
@jsweet314 in #3591 - Fix
Cannot convert object to primitive valueerror that was showing up when attempting to report a missing property on an object.
@benjie in #3618
2.3.5 (June 19, 2018)
Apollo Client (2.3.5)
- Internal code formatting updates.
- @chentsulin in #3574
- Documentation updates.
- @andtos90 in #3596
- @serranoarevalo in #3554
- @cooperka in #3594
- @pravdomil in #3587
- @excitement-engineer in #3309
Apollo Boost (0.1.10)
- No changes.
Apollo Cache (1.1.12)
- No changes.
Apollo Cache In-Memory (1.2.5)
- No changes.
Apollo Utilities (1.0.16)
- Removed unnecessary whitespace from error message.
Apollo GraphQL Anywhere (4.1.14)
- No changes.
2.3.4 (June 13, 2018)
Apollo Client (2.3.4)
- Export the
QueryOptionsinterface, to make sure it can be used by other projects (likeapollo-angular). - Fixed an issue caused by typescript changes to the constructor
defaultOptionsparam, that preventedquerydefaults from passing type checks. (@hwillson in #3585)
Apollo Boost (0.1.9)
- No changes
Apollo Cache (1.1.11)
- No changes
Apollo Cache In-Memory (1.2.4)
- No changes
Apollo Utilities (1.0.15)
- No changes
Apollo GraphQL Anywhere (4.1.13)
- No changes
2.3.3 (June 13, 2018)
Apollo Client (2.3.3)
- Typescript improvements. Made observable query parameterized on data and
variables:
ObservableQuery<TData, TVariables>(@excitement-engineer in #3140) - Added optional generics to cache manipulation methods (typescript). (@mvestergaard in #3541)
- Typescript improvements. Created a new
QueryOptionsinterface that is now used byApolloClient.queryoptions, instead of the previousWatchQueryOptionsinterface. This helps reduce confusion (especially in the docs) that made it look likeApolloClient.queryacceptedApolloClient.watchQueryonly options, likepollingInterval. (@hwillson in #3569)
Apollo Boost (0.1.8)
- Allow
cacheto be given as a configuration option toApolloBoost. (@dandean in #3561) - Allow
headersandcredentialsto be passed in as configuration parameters to theapollo-boostApolloClientconstructor. (@rzane in #3098)
Apollo Cache (1.1.10)
- Added optional generics to cache manipulation methods (typescript). (@mvestergaard in #3541)
Apollo Cache In-Memory (1.2.3)
- Added optional generics to cache manipulation methods (typescript). (@mvestergaard in #3541)
- Restore non-enumerability of
resultFields[ID_KEY]. (@benjamn in #3544) - Cache query documents transformed by InMemoryCache. (@benjamn in #3553)
Apollo Utilities (1.0.14)
- Store key names generated by
getStoreKeyNamenow leverage a more deterministic approach to handling JSON based strings. This prevents store key names from differing when usingargslike{ prop1: 'value1', prop2: 'value2' }and{ prop2: 'value2', prop1: 'value1' }. (@gdi2290 in #2869) - Avoid needless
hasOwnPropertycheck indeepFreeze. (@benjamn in #3545)
Apollo GraphQL Anywhere (4.1.12)
- No new changes.
2.3.2 (May 29, 2018)
Apollo Client (2.3.2)
- Fix SSR and
cache-and-networkfetch policy (@dastoori in #3372) - Fixed an issue where the
updateQuerymethod passed toObservableQuery.fetchMorewas receiving the original query variables, instead of the new variables that it used to fetch more data. (@abhiaiyer91 in #3500) - Fixed an issue involving
Object.setPrototypeOf()not working on JSC (Android), by instead setting theprototypeofthismanually. (@seklyza in #3306) - Added safeguards to make sure
QueryStore.initQueryandQueryStore.markQueryResultdon't try to set the network status of afetchMoreForQueryIdquery, if it does not exist in the store. This was happening when a query component was unmounted while afetchMorewas still in flight. (@conrad-vanl in #3367, @doomsower in #3469)
Apollo Boost (0.1.7)
- Various internal code cleanup, tooling and dependency changes.
Apollo Cache (1.1.9)
- Various internal code cleanup, tooling and dependency changes.
Apollo Cache In-Memory (1.2.2)
- Fixed an issue that caused fragment only queries to sometimes fail. (@abhiaiyer91 in #3507)
- Fixed cache invalidation for inlined mixed types in union fields within arrays. (@dferber90 in #3422)
Apollo Utilities (1.0.13)
- Make
maybeDeepFreezea little more defensive, by always usingObject.prototype.hasOwnProperty(to avoid cases where the object being frozen doesn't have its ownhasOwnProperty). (@jorisroling in #3418) - Remove certain small internal caches to prevent memory leaks when using SSR. (@brunorzn in #3444)