-
#10764
1b0a61fe5
Thanks @phryneas! - DeprecateuseFragment
returnPartialData
option -
#10810
a6252774f
Thanks @dleavitt! - Fix type signature ofServerError
.In <3.7
HttpLink
andBatchHttpLink
would return aServerError.message
of e.g."Unexpected token 'E', \"Error! Foo bar\" is not valid JSON"
and aServerError.result
ofundefined
in 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,
message
became e.g.Response not successful: Received status code 302
andresult
became the string from the response body, however the type inServerError.result
was not updated to include thestring
type, which is now properly reflected.
-
#10805
a5503666c
Thanks @phryneas! - Fix a potential memory leak in SSR scenarios when manypersistedQuery
instances were created over time. -
#10718
577c68bdd
Thanks @Hsifnus! - Delay Concast subscription teardown slightly inuseSubscription
to prevent unexpected Concast teardown when oneuseSubscription
hook tears down its in-flight Concast subscription immediately followed by anotheruseSubscription
hook reusing and subscribing to that same Concast
- #10735
895bcdcff
Thanks @alessbell! - If a multipart chunk contains onlyhasNext: false
, immediately complete the observable.
-
#10586
4175af594
Thanks @alessbell! - Improve WebSocket error handling for genericEvent
received on error. For more information see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event. -
#10411
152baac34
Thanks @lovasoa! - Simplify error message generation and make 'undefined' an impossible message string. -
#10592
cdb98ae08
Thanks @alessbell! - Adds support for multipart subscriptions inHttpLink
. -
#10698
38508a251
Thanks @jerelmiller! - Changes the behavior ofuseLazyQuery
introduced 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
useLazyQuery
with 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
364bee98f
Thanks @alessbell! - Upgrades TypeScript to v5. This change is fully backward-compatible and transparent to users. -
#10597
8fb9d190d
Thanks @phryneas! - Fix a bug where an incoming cache update could prevent future updates from the active link. -
#10629
02605bb3c
Thanks @phryneas! -useQuery
: delay unsubscribe to fix race conditions
-
#9438
52a9c8ea1
Thanks @dciesielkiewicz! - Ensure theclient
option passed touseMutation
's execute function is used when provided. Previously this option was ignored. -
#9124
975b923c0
Thanks @andrebrantom! - MakeApolloClient.writeQuery
andApolloClient.writeFragment
behave more likecache.writeQuery
andcache.writeFragment
by returning the reference returned by the cache.
-
#10560
a561ecf43
Thanks @benjamn! - Keep__typename
fragment when it does not contain@client
directive and strip out inline fragments which use a@client
directive. Thanks @Gazler and @mtsmfm! -
#10560
251a12806
Thanks @benjamn! - RefactorremoveDirectivesFromDocument
to fix AST ordering sensitivities and avoid 1/3 AST traversals, potentially improving performance for large queries
-
#7555
45562d6fa
Thanks @TheCeloReis! - AddsTVariables
generic toGraphQLRequest
andMockedResponse
interfaces. -
#10526
1d13de4f1
Thanks @benjamn! - Tolerate undefinedconcast.sources
ifcomplete
called earlier thanconcast.start
-
#10497
8a883d8a1
Thanks @nevir! - UpdateSingleExecutionResult
andIncrementalPayload
'sdata
types such that they no longer includeundefined
, which was not a valid runtime value, to fix errors when TypeScript'sexactOptionalPropertyTypes
is enabled.
-
#10502
315faf9ca
Thanks @jerelmiller! - Log a warning to the console when a mock passed toMockedProvider
orMockLink
cannot 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 anerrorPolicy
set toignore
, which makes it difficult to know that a match did not occur. -
#10499
9e54f5dfa
Thanks @phryneas! - Allow the execution function returned byuseLazyQuery
to change the query. -
#10362
14a56b105
Thanks @mccraveiro! - Fix error when server returns an error and we are also querying for a local field
-
#10470
47435e879
Thanks @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|undefined
into 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 thatYourGenericType
is 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
55ffafc58
Thanks @zlrlo! - fix: modify BatchHttpLink to have a separate timer for each different batch key -
#9573
4a4f48dda
Thanks @vladar! - Improve performance of local resolvers by only executing selection sets that contain an@client
directive. 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.
-
#10458
b5ccef229
Thanks @lennyburdette! - PassesgetServerSnapshot
touseSyncExternalStore
so that it doesn't trigger aMissing getServerSnapshot
error when usinguseFragment_experimental
on the server. -
#10471
895ddcb54
Thanks @alessbell! - More robust type definition forheaders
property passed tocreateHttpLink
-
#10321
bbaa3ef2d
Thanks @alessbell! - Refetch should not return partial data witherrorPolicy: none
andnotifyOnNetworkStatusChange: true
. -
#10469
328c58f90
Thanks @jerelmiller! - Add generic type defaults when usinguseFragment
to allow passingTData
directly to the function without needing to specifyTVars
.
-
#10427
28d909cff
Thanks @jerelmiller! - Ensure in-flight promises executed byuseLazyQuery
are rejected whenuseLazyQuery
unmounts. -
#10383
5c5ca9b01
Thanks @jerelmiller! - Ensure theonError
callback is called when theerrorPolicy
is set to "all" and partial data is returned. -
#10425
86e35a6d2
Thanks @jerelmiller! - Prefer theonError
andonCompleted
callback functions passed to the execute function returned fromuseMutation
instead of calling both callback handlers.
-
#10334
7d923939d
Thanks @jerelmiller! - Better handle deferred queries that have cached or partial cached data for them -
#10368
46b58e976
Thanks @alessbell! - Fix: unblocks support for defer in mutationsIf the
@defer
directive 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.
-
Only show dev tools suggestion in the console when
connectToDevTools
istrue
.
@chris110408 in #10258 -
Pass
TCache
generic toMutationHookOptions
for better type support inuseMutation
.
@igrlk in #10223 -
Add
name
property toApolloError
to ensure better type safety and help error reporting tools better identify the error.
@aaronadamsCA in #9323 -
Export a
ModifierDetails
type for thedetails
parameter of aModifier
function.
@KeithGillette in #7133 -
Revert use of
cloneDeep
to clone options when fetching queries.
@MrDoomBringer in #10215
-
Fix issue where
loading
remainstrue
afterobserver.refetch
is called repeatedly with different variables when the same data are returned.
@alessbell in #10143 -
Fix race condition where
useFragment_experimental
could receive cache updates before initially callingcache.watch
inuseEffect
.
@benjamn in #10212
-
Implement preview support for the
@defer
directive.
@alessbell and @benjamn in #10018 -
Implement
useFragment_experimental
hook, which represents a lightweight live binding into theApolloCache
, and never triggers network requests of its own.
@benjamn in #8782 -
Allow registering named fragments with
InMemoryCache
to support using...NamedFragment
in queries without redeclaringNamedFragment
repeatedly in every query that uses it.
@benjamn in #9764 -
Support
onError
callback foruseSubscription
hook.
@jeroenvisser101 in #9495 -
Implement
preserveHeaderCase
option forhttp
context object, enabling preserved header capitalization for non-http-spec-compliant servers.
@mrdoombringer in #9891
-
Delay calling
onCompleted
andonError
callbacks passed touseQuery
usingPromise.resolve().then(() => ...)
to fix issue #9794.
@dylanwulf in #9823 -
Replace
concast.cleanup
method with simplerconcast.beforeNext
API, which promises to call the given callback function just before the next result/error is delivered. In addition,concast.removeObserver
no longer takes aquietly?: boolean
parameter, since that parameter was partly responsible for cleanup callbacks sometimes not getting called.
@benjamn in #9718 -
Allow preserving header name capitalization when creating an
HttpLink
withcreateHttpLink({ uri, preserveHeaderCase: true })
. Otherwise, header names are converted to lowercase to prevent case-sensitivity bugs.
@MrDoomBringer in #9891 -
Make queries with a
pollInterval
respect theno-cache
fetch policy, instead of writing polled results into the cache.
@MrDoomBringer in #10020 -
Deprecate the
onSubscriptionData
callback in favor of a newonData
callback for theuseSubscription
hook. Deprecate theonSubscriptionComplete
callback in favor of a newonComplete
callback for theuseSubscription
hook.
@jerelmiller in #10134
- The optional
subscribeAndCount
testing utility exported from@apollo/client/testing/core
now takes a single genericTResult
type parameter, instead ofTData
. This type will typically be inferred from theobservable
argument 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
- The client options (
variables
,context
, etc.) used formutation
calls are now available as the second argument to theonCompleted
andonError
callback functions.
@MrDoomBringer in #10052
- Leave
fetchPolicy
unchanged whenskip: true
(or in standby) andnextFetchPolicy
is available, even ifvariables
change.
@benjamn in #9823
-
Fix incorrect
variables
passed inFieldFunctionOptions
for nestedreadField
calls inread
andmerge
functions.
@stardustxx in #9808 -
Improve repository build scripts to work better on Windows.
@dylanwulf in #9805 -
Ensure
useQuery(query, { skip: true }).called === false
rather than always returningcalled
astrue
.
@KucharskiPiotr in #9798 -
Allow abandoned
reobserve
requests to unsubscribe from their underlyingObservable
.
@javier-garcia-meteologica in #9791
- Fix regression (introduced in v3.6.0) that caused
BatchHttpLink
to discard pending batched queries on early completion of the underlyingObservable
.
@benjamn in #9793
- Allow
useLazyQuery(query, { defaultOptions })
to benefit fromdefaultOptions.variables
andclient.defaultOptions.watchQuery.variables
merging.
@benjamn in #9762
-
Restore pre-v3.6
variables
replacement behavior ofObservableQuery#reobserve
method, fixing a regression that prevented removal of variables.
@benjamn in #9741 -
Preserve
previousData
even when different query or client provided touseQuery
, instead of resettingpreviousData
to 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
DeepMerger
object reuse, and avoid usingObject.isFrozen
, which can introduce differences between development and production if objects that were frozen usingObject.freeze
in development are left unfrozen in production.
@benjamn in #9742 -
Properly merge
variables
from originaluseLazyQuery(query, { variables })
withvariables
passed to execution function.
@benjamn in #9758
-
Guarantee
Concast
cleanup withoutObservable cancelled prematurely
rejection, potentially solving long-standing issues involving that error.
@benjamn in #9701 -
Ensure
useSubscription
subscriptions are properly restarted after unmounting/remounting by React 18 in<StrictMode>
.
@kazekyo in #9707
-
Internalize
useSyncExternalStore
shim, for more control thanuse-sync-external-store
provides, fixing some React Native issues.
@benjamn in #9675 and #9709 -
Provide
@apollo/client/**/*.cjs.native.js
versions of every@apollo/client/**/*.cjs
bundle (including dependenciests-invariant
andzen-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
incoming
data more gracefully inoffetLimitPagination().merge
function.
@shobhitsharma in #9705
-
Simplify
useQuery(query, { defaultOptions })
default options processing in order to fix bug whereskip: true
queries failed to execute upon switching toskip: false
.
@benjamn in #9665 -
Add tests of skipping/unskipping and
useLazyQuery
withdefaultOptions
, and fix a bug causing duplicate requests.
@benjamn in #9666 -
Update
ts-invariant
to version 0.10.2 to fix source map warnings.
@benjamn in #9672 -
Test that
useQuery
queries withskip: true
do not stall server-side rendering.
@nathanmarks and @benjamn in #9677 -
Prevent
useLazyQuery
from making duplicate requests when its execution function is first called, and stop rejecting thePromise
it returns whenresult.error
is defined.
@benjamn in #9684 -
Fix issue with
useQuery
returningloading: true
state during server-side rendering withskip: true
.
@nathanmarks in #9679
- Pass
getServerSnapshot
function touseSyncExternalStore
in addition togetSnapshot
, though the two functions behave identically. This change should fix/unbreak React 18 server rendering.
@hungphongbk in #9652
- Consider
networkError.result.errors
in addition toresult.errors
inPersistedQueryLink
.
@redaid113 and @benjamn in #9410
- Remove recently-added, internal
fetchBlockingPromise
option from theWatchQueryOptions
interface, due to regressions.
@benjamn in #9504
-
Calling
fetchMore
for queries using thecache-and-network
ornetwork-only
fetch 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-first
fetch policy.
@benjamn in #9504 -
Reimplement
useQuery
anduseLazyQuery
to use the proposeduseSyncExternalStore
API from React 18.
@brainkim and @benjamn in #8785 and #9596 -
Fixed bug where the
useLazyQuery
execution function would always use therefetch
method ofObservableQuery
, instead of properly reapplying the currentfetchPolicy
using thereobserve
method.
@benjamn in #9564Since this
reobserve
method 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 existingrefetch
method. Note thatreobserve
permanently updates thevariables
and other options of theObservableQuery
, unlikerefetch({ ...variables })
, which does not save thosevariables
. -
The internal use of
options.fetchBlockingPromise
byuseQuery
anduseLazyQuery
may 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
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.
-
Allow
BatchLink
to cancel queued and in-flight operations.
@PowerKiKi and @benjamn in #9248 -
Add
GraphQLWsLink
in@apollo/client/link/subscriptions
. This link is similar to the existingWebSocketLink
in@apollo/client/link/ws
, but uses the newergraphql-ws
package and protocol instead of the oldersubscriptions-transport-ws
implementation. This functionality was technically first released in@apollo/[email protected]
, but semantically belongs in the 3.6.0 minor version. @glasser in #9369 -
Allow passing
defaultOptions
touseQuery
to avoid clobbering/resetting existing options whenuseQuery
is called repeatedly.
@benjamn in #9563, superseding #9223 -
Provide additional context to
nextFetchPolicy
functions to assist withfetchPolicy
transitions. More details can be found in thenextFetchPolicy
documentation.
@benjamn in #9222 -
Remove nagging deprecation warning about passing an
options.updateQuery
function tofetchMore
.
@benjamn in #9504 -
Let
addTypenameToDocument
take anyASTNode
(includingDocumentNode
, as before).
@benjamn in #9595 -
Set
useMutation
internalisMounted
variable totrue
again when component remounted.
@devpeerapong in #9561
-
Add
GraphQLWsLink
in@apollo/client/link/subscriptions
. This link is similar to the existingWebSocketLink
in@apollo/client/link/ws
, but uses the newergraphql-ws
package and protocol instead of the oldersubscriptions-transport-ws
implementation.
@glasser in #9369Note from @benjamn: since
GraphQLWsLink
is 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.
-
Interpret
keyFields: [...]
andkeyArgs: [...]
configurations inInMemoryCache
type/field policies asReadonlyArray
s, 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
-
Fix
useSubscription
executingskip
ped subscription when input changes.
@levrik in #9299 -
Fix partial data appearing in
useQuery().data
whennotifyOnNetworkStatusChange: true
.
@brainkim in #9367 -
Prevent
Promise
s returned byuseLazyQuery
execute functions from causing unhandledPromise
rejection errors if uncaught.
@brainkim in #9380
- Fix
refetch()
not being called whenskip
is 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.
-
Fix regression that prevented calling
onError
oronCompleted
in some cases when usinguseQuery
.
@mmahalwy in #9226 -
Make
useQuery
respectdefaultOptions.watchQuery.fetchPolicy
.
@yasharzolmajdi in #9210
- Restores old behavior where the callback passed to
useMutation()
is constant. - Fix
useMutation()
callbacks having stale closures. - Fix
useQuery()
variables being out of date.
- Remove
printer: Printer
positional parameter from publicly-exportedselectHttpOptionsAndBody
function, whose addition in #8699 was a breaking change (starting in Apollo Client 3.5.0) for direct consumers ofselectHttpOptionsAndBody
.
@benjamn in #9103
⚠️ The following advice aboutmetro.config.js
should 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/client
use a.cjs
file 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.sourceExts
configuration does not include thecjs
extension by default.As a workaround until this issue is resolved, you can configure Metro to understand the
.cjs
file extension by creating ametro.config.js
file in the root of your React Native project:// NOTE: No longer necessary in @apollo/[email protected]! const { getDefaultConfig } = require("metro-config"); const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues(); exports.resolver = { ...defaultResolver, sourceExts: [...defaultResolver.sourceExts, "cjs"], };
-
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 specified
by ensuring
import ... from 'ts-invariant/process'
is internally written toimport ... from 'ts-invariant/process/index.js'
.
@benjamn in #9083
-
Avoid rewriting non-relative imported module specifiers in
config/rewriteModuleIds.ts
script, 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
- Fix
useMutation
execute function returning non-identical execution functions when passing similar options.
@brainkim in #9037
-
Add
updateQuery
andupdateFragment
methods toApolloCache
, simplifying commonreadQuery
/writeQuery
cache 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.feed
field that takes an argument calledtype
and uses a@connection(key:...)
directive to keepfeed
data from different queries separate within the cache, you might configure both using the followingInMemoryCache
field policy:new InMemoryCache({ typePolicies: { Query: { fields: { feed: { keyArgs: ["type", "@connection", ["key"]], }, }, }, }, });
-
Report single
MissingFieldError
instead 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.identify
after traversing the fields of the object (rather than before), simplifying identification and reducing duplicate work. If you have customkeyFields
functions, they still receive the raw result object as their first parameter, but theKeyFieldsContext
parameter now providescontext.storeObject
(theStoreObject
just processed byprocessSelectionSet
) andcontext.readField
(a helper function for reading fields fromcontext.storeObject
and anyReference
s it might contain, similar toreadField
forread
,merge
, andcache.modify
functions).
@benjamn in #8996 -
Ensure
cache.identify
never throws when primary key fields are missing, and include the source object in the error message whenkeyFields
processing fails.
@benjamn in #8679 -
The
HttpLink
constructor now accepts an optionalprint
function that can be used to customize how GraphQLDocumentNode
objects are transformed back into strings before they are sent over the network.
@sarahgp in #8699 -
Make
@apollo/client/testing
a 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/core
has been created. Importing from this entry point instead of@apollo/client/testing
excludes any React-related dependencies.
@wassim-k in #8687 -
Make
cache.batch
return the result of calling theoptions.update
function.
@benjamn in #8696 -
The
NetworkError
andErrorResponse
types have been changed to align more closely.
@korywka in #8424 -
Update
zen-observable-ts
to eliminate transitive dependency on@types/zen-observable
.
@benjamn in #8695
- The
useLazyQuery
function now returns a promise with the result. - The
useMutation
result now exposes a method which can be reset.
- The
useQuery
anduseLazyQuery
hooks will now haveObservableQuery
methods defined consistently. - Calling
useLazyQuery
methods likestartPolling
will start the query. - Calling the
useLazyQuery
execution function will now behave more likerefetch
.previousData
will be preserved. standby
fetchPolicies will now act likeskip: true
more consistently.- Calling
refetch
on a skipped query will have no effect (issue #8270). - Prevent
onError
andonCompleted
functions from firing continuously, and improving their polling behavior.
- Allow
TOptions extends FieldFunctionOptions
to be passed as final (optional) type parameter ofFieldPolicy
type.
@VictorGaiva in #9000
-
Prevent webpack from misresolving the
graphql
package as the local@apollo/client/utilities/globals/graphql.js
module whenmodule.exports.resolve.preferRelative
is 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: true
from yourwebpack.config.js
file, or find a way to disable that resolution behavior for packages withinnode_modules
. -
Avoid importing
isType
from thegraphql
package internally, to prevent bundlers from including as much as 3.4kB of unnecessary code.
@benjamn in #8891 -
Make
client.resetStore
andclient.clearStore
pass appropriatediscardWatches
option tocache.reset
.
@benjamn in #8873
- Require calling
cache.reset({ discardWatches: true })
to makecache.reset
discardcache.watches
, restoring behavior broken in v3.4.14 by #8826.
@benjamn in #8852
-
Disable
InMemoryCache
result 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
InMemoryCache
watches
set 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.broadcastWatch
passes all relevantWatchOptions
tocache.diff
asDiffOptions
.
@benjamn in #8832
-
Fix
componentDidUpate
typo inwithSubscription
higher-order component.
@YarBez in #7506 -
Fix internal
canUseSymbol
import within@apollo/client/utilities
to avoid breaking bundlers/builds.
@benjamn in #8817 -
Tolerate unfreezable objects like
Uint8Array
andBuffer
inmaybeDeepFreeze
.
@geekuillaume and @benjamn in #8813
-
Improve handling of falsy
existing
and/orincoming
parameters inrelayStylePagination
field 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
- 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
- Upgrade docs theme for new Algolia-powered search experience.
@trevorblades in #8768
- Warn when calling
refetch({ variables })
instead ofrefetch(variables)
, except for queries that declare a variable named$variables
(uncommon).
@benjamn in #8702
-
Fix
ObservableQuery.getCurrentResult()
returning cacheddata
with certain fetch policies.
@brainkim in #8718 -
Prevent
ssrMode
/ssrForceFetchDelay
from causing queries to hang.
@brainkim in #8709 -
Import
@apollo/client/utilities/globals
internally wherever__DEV__
is used, not just in@apollo/client/**/index.js
entry points.
@benjamn in #8720
-
Fix unhandled
Promise
rejection 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
-
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/[email protected]
) that causedresult.data
to be set to undefined in some cases afterObservableQuery#getCurrentResult
reads an incomplete result from the cache.
@benjamn in #8642
- Fix accidental reuse of recycled
MergeTree
objects inStoreWriter
class used byInMemoryCache
.
@benjamn in #8618
-
Reevaluate
window.fetch
each timeHttpLink
uses 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/http
is first imported.
@benjamn in #8603 -
Clarify mutation
fetchPolicy
options ("network-only"
or"no-cache"
) usingMutationFetchPolicy
union type.
@benjamn in #8602
-
Restore full
@apollo/client/apollo-client.cjs.js
CommonJS bundle for older bundlers.Note that Node.js and CommonJS bundlers typically use the bundles specified by
"main"
fields in our generatedpackage.json
files, which are all independent and non-overlapping CommonJS modules. However,apollo-client.cjs.js
is just one big bundle, so mixing imports ofapollo-client.cjs.js
with the other CommonJS bundles is discouraged, as it could trigger the dual package hazard. In other words, please don't start usingapollo-client.cjs.js
if you're not already. -
Log
MissingFieldError
s inObservableQuery#getCurrentResult
usinginvariant.debug
, rather than reporting them viaresult.error
.
@benjamn in #8604
-
Fix double registration bug for mutation
refetchQueries
specified 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
/useLazyQuery
stalling when clients or queries change.
@brainkim in #8589
- Revert accidental addition of
engines.npm
section to published version of@apollo/client/package.json
.
@benjamn in #8578
- 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
- Initialize
stringifyCanon
lazily, whencanonicalStringify
is first called, fixingUncaught ReferenceError: __DEV__ is not defined
errors due to usage of__DEV__
before declaration.
@benjamn in #8557
- Refetching queries with
client.refetchQueries
.
@StephenBarlow and @benjamn in #8265
-
InMemoryCache
now 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 theObservableQuery
andCache.DiffResult
objects for any queries invalidated by cache writes performed by the mutation's finalupdate
function. UsingonQueryUpdated
, you can override the defaultFetchPolicy
of the query, by (for example) callingObservableQuery
methods likerefetch
to force a network request. This automatic detection of invalidated queries provides an alternative to manually enumerating queries using therefetchQueries
mutation option. Also, if you return aPromise
fromonQueryUpdated
, the mutation will automatically await thatPromise
, rendering theawaitRefetchQueries
option unnecessary.
@benjamn in #7827 -
Support
client.refetchQueries
as an imperative way to refetch queries, without having to passoptions.refetchQueries
toclient.mutate
.
@dannycochran in #7431 -
Improve standalone
client.refetchQueries
method to support automatic detection of queries needing to be refetched.
@benjamn in #8000 -
Fix remaining barriers to loading
@apollo/client/core
as native ECMAScript modules from a CDN like esm.run. Importing@apollo/client
from a CDN will become possible once we move all React-related dependencies into@apollo/client/react
in Apollo Client 4.
@benjamn in #8266 -
InMemoryCache
supports a new method calledbatch
, which is similar toperformTransaction
but 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 thebatch
operation.
@benjamn in #7819 -
Allow
merge: true
field policy to mergeReference
objects 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
POST
request when falling back to sending full query with@apollo/client/link/persisted-queries
.
@rieset in #7456 -
The
FetchMoreQueryOptions
type now takes two instead of three type parameters (<TVariables, TData>
), thanks to usingPartial<TVariables>
instead ofK extends typeof TVariables
andPick<TVariables, K>
.
@ArnaudBarre in #7476 -
Pass
variables
andcontext
to a mutation'supdate
function. Note: The type of theupdate
function is now namedMutationUpdaterFunction
rather thanMutationUpdaterFn
, since the older type was broken beyond repair. If you are usingMutationUpdaterFn
in your own code, please useMutationUpdaterFunction
instead.
@jcreighton in #7902 -
A
resultCacheMaxSize
option may be passed to theInMemoryCache
constructor 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
InMemoryCache
by eviction, or by any other means.
@sofianhn and @benjamn in #8147 -
Add expected/received
variables
toNo more mocked responses...
error messages generated byMockLink
.
@markneub in #8340 -
The
InMemoryCache
version of thecache.gc
method 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
-
To avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4 automatically clears any
ROOT_MUTATION
fields 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: true
option toclient.mutate
.ROOT_MUTATION
result data are also passed to the mutationupdate
function, 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 atrue
orfalse
constant, the same way you already replaceprocess.env.NODE_ENV
with 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.ts
files). This change should remove any need to configureesModuleInterop
orallowSyntheticDefaultImports
intsconfig.json
, but might require updating bundler configurations that specify named exports of thereact
andprop-types
packages, to include exports likecreateContext
andcreateElement
(example).
@devrelm in #7742 -
Respect
no-cache
fetch policy (by not reading anydata
from the cache) forloading: true
results triggered bynotifyOnNetworkStatusChange: true
.
@jcreighton in #7761 -
The TypeScript return types of the
getLastResult
andgetLastError
methods ofObservableQuery
now 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-undefined
results.
@benjamn in #8394 -
Log non-fatal
invariant.error
message 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@client
is 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
nextFetchPolicy
option forclient.watchQuery
anduseQuery
will no longer be removed from theoptions
object after it has been applied, and instead will continue to be applied any timeoptions.fetchPolicy
is reset to another value, until/unless theoptions.nextFetchPolicy
property is removed fromoptions
.
@benjamn in #8465 -
The
fetchMore
,subscribeToMore
, andupdateQuery
functions returned from theuseQuery
hook may now return undefined in edge cases where the functions are called when the component is unmounted
@noghartt in #7980.
-
In Apollo Client 2.x, a
refetch
operation would always replace existing data in the cache. With the introduction of field policymerge
functions in Apollo Client 3, existing field values could be inappropriately combined with incoming field values by a custommerge
function that does not realize arefetch
has happened.To give you more control over this behavior, we have introduced an
overwrite?: boolean = false
option forcache.writeQuery
andcache.writeFragment
, and an option calledrefetchWritePolicy?: "merge" | "overwrite"
forclient.watchQuery
,useQuery
, and other functions that acceptWatchQueryOptions
. You can use these options to make sure anymerge
functions involved in cache writes forrefetch
operations get invoked withundefined
as their first argument, which simulates the absence of any existing data, while still giving themerge
function a chance to determine the internal representation of the incoming data.The default behaviors are
overwrite: true
andrefetchWritePolicy: "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 forrefetchWritePolicy
indefaultOptions.watchQuery
:new ApolloClient({ defaultOptions: { watchQuery: { refetchWritePolicy: "merge", }, }, });
-
Make sure the
MockedResponse
ResultFunction
type is re-exported.
@hwillson in #8315 -
InMemoryCache
now coalescesEntityStore
updates to guarantee only onestore.merge(id, fields)
call perid
per 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#getCurrentResult
always callqueryInfo.getDiff()
.
@benjamn in #8422 -
Make
readField
default to reading from current object only when thefrom
option/argument is actually omitted, not whenfrom
is passed toreadField
with an undefined value. A warning will be printed when this situation occurs.
@benjamn in #8508 -
The
fetchMore
,subscribeToMore
, andupdateQuery
functions no longer throwundefined
errors
@noghartt in #7980.
-
Fix race condition in
@apollo/client/link/context
that could leak subscriptions if the subscription is cancelled beforeoperation.setContext
is called.
@sofianhn in #8399 -
Prefer
existing.pageInfo.startCursor
andendCursor
(if defined) inread
function ofrelayStylePagination
policies.
@benjamn in #8438
- Fix policy merging bug when calling
cache.policies.addTypePolicies
multiple times for the same type policy.
@Banou26 in #8361
- Use
export ... from
syntax to re-exportgraphql-tag
named exports, making tree-shaking easier for some bundlers.
@benjamn in #8221
- Replace Spectrum references with community.apollographql.com.
@hwillson in #8238
- Add
"sideEffects": false
to all generated/publishedpackage.json
files, to improve dead code elimination for nested entry points like@apollo/client/cache
.
@benjamn in #8213
- Make
useReactiveVar(rv)
recheck the latestrv()
value in itsuseEffect
callback, and immediately update state if the value has already changed, rather than callingrv.onNextChange(setValue)
to listen for future changes.
@benjamn in #8135
-
Prevent
undefined
mutation result inuseMutation
.
@jcreighton in #8018 -
Fix
useReactiveVar
not rerendering for successive synchronous calls.
@brainkim in #8022 -
Support
batchDebounce
option forBatchLink
andBatchHttpLink
.
@dannycochran in #8024
-
Increment
queryInfo.lastRequestId
only when making a network request through theApolloLink
chain, rather than every timefetchQueryByPolicy
is called.
@dannycochran in #7956 -
During server-side rendering, allow initial
useQuery
calls to return final{ loading: false, data }
results when the cache already contains the necessary data.
@benjamn in #7983
- Adjust TypeScript types to allow
keyFields
andkeyArgs
functions to returnfalse
.
@CarsonF and @benjamn in #7900
-
Prevent
RenderPromises
memory leak by callingrenderPromises.clear()
aftergetMarkupFromTree
finishes.
@benjamn in #7943 -
Cancel pending notify timeout when stopping a
QueryInfo
object.
@hollandThomas in #7935 -
Fix infinite rendering bug related to
useSubscription
.
@brainkim in #7917
-
Add missing
context
option touseSubscription
.
@jcreighton in #7860 -
Remove unnecessary TypeScript global
Observable<T>["@@observable"]
method declaration.
@benjamn in #7888 -
Prevent skipped/observerless
ObservableQuery
s from being refetched byrefetchQueries
.
@dannycochran in #7877
-
Maintain serial ordering of
asyncMap
mapping function calls, and prevent potential unhandledPromise
rejection errors.
@benjamn in #7818 -
Relax incompatible
children?: React.ReactElement
field type inMockedProviderProps
interface.
@kevinperaza in #7833
- Fix
useLazyQuery
forceUpdate
loop regression introduced by #7655 in version 3.3.10.
@benjamn in #7715
-
Revert PR #7276, but test that garbage collection reclaims torn-down
ObservableQuery
objects.
@benjamn in #7695 -
Reset
QueryInfo.diff
andQueryInfo.dirty
after canceling notify timeout inQueryInfo.markResult
andQueryInfo.markError
.
@jcreighton in #7696
-
Avoid calling
forceUpdate
when component is unmounted.
@DylanVann in #7655 -
The
codemods/
top-level directory has been moved into thescripts/
directory.
@benjamn in #7675
- Prevent reactive variables from retaining otherwise unreachable
InMemoryCache
objects.
@benjamn in #7661
- The
graphql-tag
dependency 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
-
Catch updates in
useReactiveVar
with an additional check.
@jcreighton in #7652 -
Reactivate forgotten reactive variables whenever
InMemoryCache
acquires its first watcher.
@benjamn in #7657 -
Backport
Symbol.species
fix forConcast
andObservableQuery
fromrelease-3.4
, fixing subscriptions in React Native Android when the Hermes JavaScript engine is enabled (among other benefits).
@benjamn in #7403 and #7660
-
Fix a regression due to #7310 that caused
loading
always to betrue
forskip: true
results during server-side rendering.
@rgrove in #7567 -
Avoid duplicate
useReactiveVar
listeners when rendering inReact.StrictMode
.
@jcreighton in #7581
- Set
displayName
onApolloContext
objects for easier debugging.
@dulmandakh in #7550
-
Immediately apply
queryType: true
,mutationType: true
, andsubscriptionType: true
type policies, rather than waiting for the first time the policy is used, fixing a regression introduced by #7065.
@benjamn in #7463 -
Check that
window
is defined even whenconnectToDevTools
istrue
.
@yasupeke in #7434
-
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
- Restore
client.version
property, reflecting the current@apollo/client
version frompackage.json
.
@benjamn in #7448
- Update
ts-invariant
to avoid potential Content Security Policy-violatingFunction
fallback, thanks to a clever newglobalThis
polyfill technique.
@benjamn in #7414
- Make the
observer
parameter ofApolloLink#onError
optional, fixing an unnecessary breaking change for any code that calledonError
directly.
@benjamn in #7407
⚠️ Note: This version of@apollo/client
contains no behavioral changes since version 3.3.1
-
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
ApolloLink
to 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
- Revert back to
default
-importingReact
internally, rather than using a namespace import.
@benjamn in 113475b1
-
Update
@wry/equality
to consider undefined properties equivalent to missing properties.
@benjamn in #7108 -
Prevent memory leaks involving unused
onBroadcast
function closure created inApolloClient
constructor.
@kamilkisiela in #7161 -
Provide default empty cache object for root IDs like
ROOT_QUERY
, to avoid differences in behavior before/afterROOT_QUERY
data has been written intoInMemoryCache
.
@benjamn in #7100 -
Cancel
queryInfo.notifyTimeout
inQueryInfo#markResult
to prevent unnecessary network requests when using aFetchPolicy
ofcache-and-network
ornetwork-only
in a React component with multipleuseQuery
calls.
@benjamn in #7347
-
Ensure
cache.readQuery
andcache.readFragment
always returnTData | null
, instead of throwingMissingFieldError
exceptions when missing fields are encountered.
@benjamn in #7098Since this change converts prior exceptions to
null
returns, and sincenull
was already a possible return value according to theTData | null
return type, we are confident this change will be backwards compatible (as long asnull
was properly handled before). -
HttpLink
will now automatically strip any unusedvariables
before 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: true
to theHttpLink
constructor (which is typically passed asoptions.link
to theApolloClient
constructor).
@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 theerror
property of a result.
@hwillson in #7110Returning mock configuration errors through the Link's
Observable
was 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
ObservableQuery
will once again unsubscribe from the underlying networkObservable
in 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
QueryBaseOptions
andModifiableWatchQueryOptions
interface supertypes have been eliminated, and their fields are now defined byQueryOptions
.
@DCtheTall in #7136 -
Internally, Apollo Client now avoids nested imports from the
graphql
package, 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
graphql
package uses.mjs
modules, your bundler may need to be configured to recognize.mjs
files as ECMAScript modules rather than CommonJS modules.
@benjamn in #7185
-
Support inheritance of type and field policies, according to
possibleTypes
.
@benjamn in #7065 -
Allow configuring custom
merge
functions, including themerge: true
andmerge: false
shorthands, in type policies as well as field policies.
@benjamn in #7070 -
The verbosity of Apollo Client console messages can be globally adjusted using the
setLogVerbosity
function: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 messages
Remember that all logs, warnings, and errors are hidden in production.
@benjamn in #7226 -
Modifying
InMemoryCache
fields that havekeyArgs
configured will now invalidate only the field value with matching key arguments, rather than invalidating all field values that share the same field name. IfkeyArgs
has not been configured, the cache must err on the side of invalidating by field name, as before.
@benjamn in #7351 -
Shallow-merge
options.variables
when 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.data
property,useQuery
anduseLazyQuery
will now provide aresult.previousData
property, which can be useful when a network request is pending andresult.data
is undefined, sinceresult.previousData
can be rendered instead of rendering an empty/loading state.
@hwillson in #7082 -
Passing
validate: true
to theSchemaLink
constructor 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 forInMemoryCache
field policies.
@benjamn in #7109 -
Avoid registering
QueryPromise
whenskip
istrue
during server-side rendering.
@izumin5210 in #7310 -
ApolloCache
objects (includingInMemoryCache
) may now be associated with or disassociated from individual reactive variables by callingreactiveVar.attachCache(cache)
and/orreactiveVar.forgetCache(cache)
.
@benjamn in #7350
- Revert back to
default
-importingReact
internally, rather than using a namespace import.
@benjamn in 113475b1
-
Ensure
sourcesContent
array is properly defined in.js.map
files generated bytsc
.
@benjamn in #7371 -
Avoid relying on global
Symbol
properties inApolloContext.ts
.
@benjamn in #7371
- Revert updating
symbol-observable
from version 2.x to version 3, which caused TypeScript errors with some@types/node
versions, especially in Angular applications.
@benjamn in #7340
-
Always consider singleton IDs like
ROOT_QUERY
andROOT_MUTATION
to be root IDs duringcache.gc
garbage collection, regardless of whether they have been retained or released.
@benjamn in #7333 -
Use optional chaining syntax (
this.currentObservable?.refetch
) in Reactrefetch
wrapper function to avoid crashing when an unmounted component is accidentally refetched.
@tm1000 in #6314 and @linmic in #7186
-
Handle older
react-apollo
package incodemods/ac2-to-ac3/imports.js
migration script.
@tm1000 in #7216 -
Ensure
relayStylePagination
preservespageInfo.{start,end}Cursor
ifedges
is missing or empty.
@beaucollins in #7224
-
Move
terser
dependency fromdependencies
todevDependencies
.
@SimenB in #7188 -
Avoid all sub-package imports from the
graphql
npm package.
@stoically in #7185
-
Update the
optimism
npm dependency to version 0.13.0 in order to use the newoptimistic.forget
method to fix a potentialcache.watch
memory leak.
@benjamn in #7157 -
Consider
cache.reset
a destructive method, likecache.evict
andcache.modify
.
@joshjg in #7150 -
Avoid refetching observerless queries with
reFetchObservableQueries
.
@joshjg in #7146
- Undo
TEdgeWrapper
approach forrelayStylePagination
, introduced by f41e9efc in #7023, since it was an unintended breaking change for existing code that usedcache.modify
to interact with field data managed byrelayStylePagination
.
@benjamn in #7103
-
Fix
relayStylePagination
to handle the possibility that edges might be normalizedReference
objects (uncommon).
@anark and @benjamn in #7023 -
Disable "Missing cache result fields" warnings when
returnPartialData
istrue
.
@hwillson in #7055
- Mark
subscriptions-transport-ws
peerDependency
as optional.
@MasterOdin in #7047
-
Use
options.nextFetchPolicy
internally to restore originalFetchPolicy
after polling withfetchPolicy: "network-only"
, so that polling does not interfere with normal query watching.
@benjamn in #6893 -
Initialize
ObservableQuery
inupdateObservableQuery
even ifskip
istrue
.
@mu29 in #6999 -
Prevent full reobservation of queries affected by optimistic mutation updates, while still delivering results from the cache.
@benjamn in #6854
-
In TypeScript, all APIs that take
DocumentNode
parameters 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
possibleTypes
to 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.nextFetchPolicy
to be a function that takes the currentFetchPolicy
and returns a new (or the same)FetchPolicy
, makingnextFetchPolicy
more suitable for global use indefaultOptions.watchQuery
.
@benjamn in #6893 -
Implement
useReactiveVar
hook for consuming reactive variables in React components.
@benjamn in #6867 -
Move
apollo-link-persisted-queries
implementation 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.evict
orcache.modify
operation.
@benjamn in #6817 and #6898 -
Throw if
writeFragment
cannot identifyoptions.data
when nooptions.id
provided.
@jcreighton in #6859 -
Provide
options.storage
object tocache.modify
functions, as provided toread
andmerge
functions.
@benjamn in #6991 -
Allow
cache.modify
functions 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
ErrorPolicy
values (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
FetchPolicy
ofcache-only
inObservableQuery#refetch
.
@benjamn in ccb0a79a, fixing #6702
-
Restrict root object identification to
ROOT_QUERY
(the ID corresponding to the rootQuery
object), allowingMutation
andSubscription
as user-defined types.
@benjamn in #6914 -
Prevent crash when
pageInfo
and emptyedges
are received byrelayStylePagination
.
@fracmak in #6918
- Consider only
result.data
(rather than all properties ofresult
) when settling cache feuds.
@danReynolds in #6777
- Provide jscodeshift transform for automatically converting Apollo Client 2.x
import
declarations to use Apollo Client 3.x packages. Instructions.
@dminkovsky and @jcreighton in #6486
- Re-export cache types from
@apollo/client/core
(and thus also@apollo/client
), again.
@benjamn in #6725
-
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 (likeonCompleted
andonError
) inuseQuery
options, since those functions are almost always freshly evaluated each timeuseQuery
is called.
@hwillson and @benjamn in #6588 -
Respect
context.queryDeduplication
if provided, and otherwise fall back toclient.deduplication
(as before).
@igaloly in #6261 and @Kujawadl in #6526 -
Refactor
ObservableQuery#getCurrentResult
to reenable immediate delivery of warm cache results. As part of this refactoring, theApolloCurrentQueryResult
type was eliminated in favor ofApolloQueryResult
.
@benjamn in #6710 -
Avoid clobbering
defaultOptions
withundefined
values.
@benjamn in #6715
-
Apollo Client will no longer modify
options.fetchPolicy
unless you passoptions.nextFetchPolicy
to request an explicit change inFetchPolicy
after the current request. Although this is technically a breaking change,options.nextFieldPolicy
makes it easy to restore the old behavior (by passingcache-first
).
@benjamn in #6712, reverting #6353 -
Errors of the form
Invariant Violation: 42
thrown in production can now be looked up much more easily, by consulting the auto-generated@apollo/client/invariantErrorCodes.js
file specific to your@apollo/client
version.
@benjamn in #6665 -
Make the
client
field of theMutationResult
type non-optional, since it is always provided.
@glasser in #6617 -
Allow passing an asynchronous
options.renderFunction
togetMarkupFromTree
.
@richardscarrott in #6576 -
Ergonomic improvements for
merge
andkeyArgs
functions in cache field policies.
@benjamn in #6714
- Avoid duplicating
graphql/execution/execute
dependency in CommonJS bundle for@apollo/client/link/schema
, fixinginstanceof
errors reported in #6621 and #6614.
@benjamn in #6624
-
Make sure
useQuery
onCompleted
is not fired whenskip
istrue
.
@hwillson in #6589 -
Revert changes to
peerDependencies
inpackage.json
(#6594), which would have allowed using incompatible future versions ofgraphql
and/orreact
due to overly-permissive>=
version constraints.
@hwillson in #6605
⚠️ Note: As of 3.0.0, Apollo Client uses a new package name:@apollo/client
-
[BREAKING]
ApolloClient
is now only available as a named export. The defaultApolloClient
export has been removed.
@hwillson in #5425 -
[BREAKING] The
queryManager
property ofApolloClient
instances 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
ObservableQuery
consumers, 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 publicgraphQLErrors
andnetworkError
properties.
@lorensr in #3892 -
[BREAKING] Support for the
@live
directive 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
@client
fields to be passed into thelink
chain ifresolvers
were not set in the constructor. This allowed@client
fields to be passed into Links likeapollo-link-state
. Apollo Client 3 enforces that@client
fields are local only, meaning they are no longer passed into thelink
chain, under any circumstances.
@hwillson in #5982 -
[BREAKING?] Refactor
QueryManager
to make better use of observables and enforcefetchPolicy
more reliably.
@benjamn in #6221 -
The
updateQuery
function previously required byfetchMore
has been deprecated with a warning, and will be removed in the next major version of Apollo Client. Please consider using amerge
function 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 typicalupdateQuery
functions. 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-common
andapollo-link-http
packages is now directly available from@apollo/client
(e.g.import { HttpLink } from '@apollo/client'
). TheApolloClient
constructor has also been updated to accept newuri
,headers
andcredentials
options. Ifuri
is specified, Apollo Client will take care of creating the necessaryHttpLink
behind the scenes.
@hwillson in #5412 -
The
gql
template tag should now be imported from the@apollo/client
package, rather than thegraphql-tag
package. Although thegraphql-tag
package still works for now, future versions of@apollo/client
may change the implementation details ofgql
without a major version bump.
@hwillson in #5451 -
@apollo/client/core
can be used to import the Apollo Client core, which includes everything the main@apollo/client
package does, except for all React related functionality.
@kamilkisiela in #5541 -
Several deprecated methods have been fully removed:
ApolloClient#initQueryManager
QueryManager#startQuery
ObservableQuery#currentResult
-
Apollo Client now supports setting a new
ApolloLink
(or link chain) afternew ApolloClient()
has been called, using theApolloClient#setLink
method.
@hwillson in #6193 -
The final time a mutation
update
function 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 #
⚠️ Note:InMemoryCache
has 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
InMemoryCache
constructor should now be imported directly from@apollo/client
, rather than from a separate package. Theapollo-cache-inmemory
package is no longer supported.The
@apollo/client/cache
entry point can be used to importInMemoryCache
without importing other parts of the Apollo Client codebase.
> @hwillson in #5577 -
[BREAKING]
FragmentMatcher
,HeuristicFragmentMatcher
, andIntrospectionFragmentMatcher
have all been removed. We now recommend usingInMemoryCache
’spossibleTypes
option instead. For more information see the DefiningpossibleTypes
manually 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]
InMemoryCache
will 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 custommerge
function is defined by a field policy for that field, within a type policy associated with the__typename
of the parent object.
@benjamn in #5603 -
[BREAKING]
InMemoryCache
now 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.writeData
have been fully removed.writeData
usage 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.modify
can be used to update the cache.
@benjamn in #5923 -
InMemoryCache
now supports tracing garbage collection and eviction. Note that the signature of theevict
method has been simplified in a potentially backwards-incompatible way.
@benjamn in #5310-
[beta-BREAKING] Please note that the
cache.evict
method now requiresCache.EvictOptions
, though it previously supported positional arguments as well.
@danReynolds in #6141 @benjamn in #6364 -
Removing an entity object using the
cache.evict
method 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 fieldread
function 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: boolean
property 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 -
InMemoryCache
nowconsole.warn
s in development whenever non-normalized data is dangerously overwritten, with helpful links to documentation about normalization and custommerge
functions.
@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 -
InMemoryCache
now has a method calledmodify
which 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.evict
method is now implemented in terms ofcache.modify
.
@benjamn in #5909 and #6178 -
InMemoryCache
provides 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 error
These 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.readQuery
andcache.writeQuery
methods now accept anoptions.id
string, which eliminates most use cases forcache.readFragment
andcache.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#evict
remove data from allEntityStore
layers.
@benjamn in #5773 -
Stop paying attention to
previousResult
inInMemoryCache
.
@benjamn in #5644 -
Improve optimistic update performance by limiting cache key diversity.
@benjamn in #5648 -
Custom field
read
functions 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
modify
andidentify
to the mutateupdate
function.
@hwillson in #5956 -
Add a default
gc
implementation toApolloCache
.
@justinwaite in #5974
-
[BREAKING] The
QueryOptions
,MutationOptions
, andSubscriptionOptions
React Apollo interfaces have been renamed toQueryDataOptions
,MutationDataOptions
, andSubscriptionDataOptions
(to avoid conflicting with similarly named and exported Apollo Client interfaces). -
[BREAKING] Results with
loading: true
will 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 withMap
orSet
operations 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.js
is not included in your bundle.
@benjamn in #5962 -
The contents of the
@apollo/react-hooks
package 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/client
bundle.
@hwillson in #6499
-
[BREAKING] Removed
graphql-anywhere
since it's no longer used by Apollo Client.
@hwillson in #5159 -
[BREAKING] Removed
apollo-boost
since 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-utilities
package are now only available by importing from@apollo/client/utilities
.
> @hwillson in #5683 -
Make sure all
graphql-tag
public 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
ApolloContext
plays 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/components
and@apollo/client/react/hoc
entry points.
@hwillson in #6558 -
Support passing a
context
object through the link execution chain when using subscriptions.
@sgtpepper43 in #4925 -
MockSubscriptionLink
now supports multiple subscriptions.
@dfrankland in #6081
-
useMutation
adjustments to help avoid an infinite loop / too many renders issue, caused by unintentionally modifying theuseState
based mutation result directly.
@hwillson in #5770 -
Missing
__typename
fields no longer cause theInMemoryCache#diff
result to be markedcomplete: false
, if those fields were added byInMemoryCache#transformDocument
(which callsaddTypenameToDocument
).
@benjamn in #5787 -
Fixed an issue that allowed
@client @export
based queries to lead to extra unnecessary network requests being fired.
@hwillson in #5946 -
Refined
useLazyQuery
types to help prevent runtime errors.
@benmosher in #5935 -
Make sure
@client @export
variables used in watched queries are updated each time the query receives new data that changes the value of the@export
variable.
@hwillson in #5986 -
Ensure
useMutation
passes a definederrorPolicy
option 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 (facebook/react#17099).
@hwillson in #6107 -
Expand
ApolloError
typings to includeServerError
andServerParseError
.
@dmarkow in #6319 -
Fast responses received over the link chain will no longer conflict with
skip
settings.
@hwillson in #6587
-
Update the
fetchMore
type signature to acceptcontext
.
@koenpunt in #5147 -
Fix type for
Resolver
and use it in the definition ofResolvers
.
@peoplenarthax in #4943 -
Local state resolver functions now receive a
fragmentMap: FragmentMap
object, in addition to thefield: FieldNode
object, via theinfo
parameter.
@mjlyons in #5388 -
Documentation updates.
@tomquirk in #5645
@Sequoia in #5641
@phryneas in #5628
@AryanJ-NYC in #5560
- Fix
filter
edge case involvingnull
.
@lifeiscontent in #5110
-
Replace
GlobalFetch
reference withWindowOrWorkerGlobalScope
.
@abdonrd in #5373 -
Add
assumeImmutableResults
typing to apollo boostPresetConfig
interface.
@bencoullie in #5571
-
Modify
ObservableQuery
to allow queries withnotifyOnNetworkStatusChange
to be notified when loading after an error occurs.
@jasonpaulos in #4992 -
Add
graphql
as apeerDependency
ofapollo-cache
andgraphql-anywhere
.
@ssalbdivad in #5081
- A new
ObservableQuery.resetQueryStoreErrors()
method is now available that can be used to clear outObservableQuery
query store errors.
@hwillson in #4941 - Documentation updates.
@michael-watson in #4940
@hwillson in #4969
- In all Apollo Client packages, the compilation of
lib/bundle.esm.js
tolib/bundle.cjs.js
andlib/bundle.umd.js
now uses Babel instead of Rollup, since Babel correctly compiles some edge cases that neither Rollup nor TypeScript compile correctly.
@benjamn in #4911
- The
isEqual
function has been reimplemented using thelodash.isequal
npm package, to better support circular references. Since thelodash.isequal
package is already used byreact-apollo
, this change is likely to decrease total bundle size.
@capaj in #4915
- 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
-
If you can be sure your application code does not modify cache result objects (see
freezeResults
note 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-dedup
package.
@benjamn in commit 7cd8479f -
The
FetchPolicy
type has been split into two types, so that passingcache-and-network
toApolloClient#query
is now forbidden at the type level, whereas previously it was forbidden by a runtimeinvariant
assertion: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
fetchPolicy
is'no-cache'
.
@bradleyayers in PR #4573, part of issue #3452 -
Remove temporary
queryId
afterfetchMore
completes.
@doomsower in #4440 -
Call
clearStore
callbacks after clearing store.
@ds8k in #4695 -
Perform all
DocumentNode
transforms once, and cache the results.
@benjamn in #4601 -
Accommodate
@client @export
variable changes inObservableQuery
.
@hwillson in #4604 -
Support the
returnPartialData
option for watched queries again.
@benjamn in #4743 -
Preserve
networkStatus
for incompletecache-and-network
queries.
@benjamn in #4765 -
Preserve
cache-and-network
fetchPolicy
when 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
-
Support
new InMemoryCache({ freezeResults: true })
to help enforce immutability.
@benjamn in #4514 -
Allow
IntrospectionFragmentMatcher
to match fragments against the rootQuery
, asHeuristicFragmentMatcher
does.
@rynobax in #4620 -
Rerential identity (
===
) of arrays in cache results will now be preserved for unchanged data.
@benjamn in commit f3091d6a -
Avoid adding
__typename
field to@client
selection sets that have been@export
ed as input variables.
@benjamn in #4784
- The
graphql
function can now be configured to ignore@include
and@skip
directives (useful when walking a fragment to generate prop types or filter result data).
@GreenGremlin in #4373
- Introduces new local state management features (client-side schema
and local resolver /
@client
support) 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
QueryManager
was accidentally returning cached data fornetwork-only
queries.
@danilobuerger in #4352 - Fixed an issue in the repo
.gitattributes
that was causing binary files to have their line endings adjusted, and cleaned up corrupted documentation images (ref: apollographql#4232).
@rajington in #4438 - Improve (and shorten) query polling implementation.
PR #4337
-
Resolve "invalidate" -> "invalidated" typo in
QueryManager
.
@quazzie in #4041 -
Properly type
setQuery
and fix now typed callers.
@danilobuerger in #4369 -
Align with the React Apollo decision that result
data
should beTData | undefined
instead 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
- Support
ApolloClient#stop
method for safe client disposal.
PR #4336
- Added explicit dependencies on the
tslib
package to all client packages to fix Issue #4332.
- Reverted some breaking changes accidentally released in a patch version (2.4.10). PR #4334
-
The
apollo-client
package no longer exports aprintAST
function 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
setTimeout
interval rather than multiplesetInterval
timers. 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
-
The
optimism
npm 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.stringify
instead of theprint
function exported by thegraphql
package, to avoid pulling unnecessary printing logic into your JavaScript bundle.
PR #4234 -
The
QueryKeyMaker
abstraction 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
-
The
flattenSelections
helper function is no longer exported fromapollo-utilities
, sincegetDirectiveNames
has been reimplemented without usingflattenSelections
, andflattenSelections
has 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 has been updated to use
graphql
14.x as a dev dependency.
@hwillson in #4233 -
The
onClearStore
function can now be used to register callbacks that should be triggered when callingclearStore
.
@joe-re in #4082 -
Make
isApolloError
available for external use.
@FredyC in #4223 -
The
QueryManager
now callscomplete
on 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
- Transformation utilities have been refactored to work with
graphql
14.x. GraphQL AST's are no longer being directly modified.
@hwillson in #4233
-
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
RecordingCache
abstraction has been removed, and thus is no longer exported fromapollo-cache-inmemory
.
PR #4319 -
Export the optimism
wrap
function using ES2015 export syntax, instead of CommonJS.
@ardatan in #4158
-
Documentation and config updates.
@justinanastos in #4187
@PowerKiKi in #3693
@nandito in #3865 -
Schema/AST tranformation utilities have been updated to work properly with
@client
directives.
@justinmakaila in #3482
-
Avoid using
DepTrackingCache
for optimistic reads. PR #4521 -
When creating an
InMemoryCache
object, 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.
- The
ApolloClient
constructor has been updated to acceptname
andversion
params, 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
- No changes.
- No changes.
- No changes.
- No changes.
- No changes.
-
Added some
return
s to prevent errors withnoImplicitReturns
TypeScript rule. PR #4137 -
Exclude the
src/
directory when publishingapollo-cache-inmemory
. Issue #4083
-
Optimistic tests cleanup. PR #3834 by @joshribakoff
-
Documentation updates. PR #3840 by @chentsulin and PR #3844 by @lorensr
-
Implement
ObservableQuery#isDifferentFromLastResult
to fix Issue #4054 and Issue #4031. PR #4069
- Add
readQuery
test to make sure options aren't mutated. @CarloPalinckx in #3838
- Avoid modifying source objects when merging cache results. Issue #4081 PR #4089
-
Discard property accessor functions in
cloneDeep
helper, to fix issue #4034. -
Unconditionally remove
cloneDeep
property accessors. PR #4039 -
Avoid copying non-enumerable and/or
Symbol
keys incloneDeep
. PR #4052
-
Throw when querying non-scalar objects without a selection set. Issue #4025 PR #4038
-
Work around spec non-compliance of
Map#set
andSet#add
in IE11. Issue #4024 PR #4012
-
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
ObservableQuery
class now makes a deep clone oflastResult
when first received, so that theisDifferentResult
logic will not be confused if the result object is modified later. Issue #3992 PR #4032
-
Optimize repeated
apollo-cache-inmemory
reads 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#executeStoreQuery
andexecuteSelectionSet
, and work around bugs in the React NativeMap
andSet
polyfills. PR #3964 React Native PR #21492 (pending) -
The
apollo-cache-inmemory
package now allowsgraphql@^14.0.0
as a peer dependency. Issue #3978 -
The
apollo-cache-inmemory
package 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
- Make
graphql-anywhere
filter
function generic (typescript).
@minznerjosh in #3929
- The
fclone
package has been replaced with a customcloneDeep
implementation that is tolerant of cycles, symbol properties, and non-enumerable properties. PR #4032
- Remove duplicate InMemoryCache export for Babel 6 compatibility. Issue #3910 PR #3932
- No changes.
- Apollo Client no longer deep freezes query results. @hwillson in #3883
- A new
clearStore
method 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
- Replace the custom
cloneDeep
implementation withfclone
, to avoid crashing when encountering circular references.
@hwillson in #3881
- No changes.
- No changes.
- No changes.
- No changes.
-
mutate
'srefetchQueries
option now allows queries to include a customcontext
option. Thiscontext
will 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_QUERY
above 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
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
- Various internal infrastructure changes related to building, bundling, testing, etc. @hwillson in #3817
- Add proper error handling for subscriptions. If you have defined an
error
handler on your subscription observer, it will now be called when an error comes back in a result, and thenext
handler will be skipped (similar to how we're handling errors with mutations). Previously, the error was just passed in the result to thenext
handler. If you don't have anerror
handler 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
optimistic
param to be passed intoApolloClient.readQuery
andApolloClient.readFragment
, that when set totrue
, will allow optimistic results to be returned. Isfalse
by 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
- No changes.
- No changes.
- No changes.
- No changes.
- Adjusted the
graphql
peer 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 usinggraphql
0.12.x or 0.13.x.
@hwillson in #3746 - Document
setVariables
internal API status.
@PowerKiKi in #3692 - Corrected
ApolloClient.queryManager
typing as it may beundefined
.
@danilobuerger in #3661 - Make sure using a
no-cache
fetch policy with subscriptions prevents data from being cached.
@hwillson in #3773 - Fixed an issue that sometimes caused empty query results, when using the
no-cache
fetch 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
- No changes.
- No changes.
- No changes.
- No changes.
- No changes.
- Release 2.3.6 broke Typescript compilation.
QueryManager
'sgetQueryWithPreviousResult
method included an invalidvariables
return type in the auto-generatedcore/QueryManager.d.ts
declaration 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.getQueryWithPreviousResult
return types are now excplicity identified, which helps Typescript avoid the local type reference. For more details, see apollographql#3729.
@hwillson in #3731
- No changes.
- 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
graphql
peerDependencies
to handle 14.x versions.
@ivank in #3598 - Add optional generic type params for variables on low level methods.
@mvestergaard in #3588 - Add a new
awaitRefetchQueries
config option to the Apollo Clientmutate
function, that when set totrue
will wait for allrefetchQueries
to be fully refetched, before resolving the mutation call.awaitRefetchQueries
isfalse
by default.
@jzimmek in #3169
- Allow
fetch
to be given as a configuration option toApolloBoost
.
@mbaranovski in #3590 - The
apollo-boost
ApolloClient
constructor now warns about unsupported options.
@quentin- in #3551
- No changes.
- Add
__typename
andid
properties todataIdFromObject
parameter (typescript)
@jfurler in #3641 - Fixed an issue caused by
dataIdFromObject
considering 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
- No changes.
- Add support for arrays to
graphql-anywhere
's filter utility.
@jsweet314 in #3591 - Fix
Cannot convert object to primitive value
error that was showing up when attempting to report a missing property on an object.
@benjie in #3618
- 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
- No changes.
- No changes.
- No changes.
- Removed unnecessary whitespace from error message.
- No changes.
- Export the
QueryOptions
interface, to make sure it can be used by other projects (likeapollo-angular
). - Fixed an issue caused by typescript changes to the constructor
defaultOptions
param, that preventedquery
defaults from passing type checks. (@hwillson in #3585)
- No changes
- No changes
- No changes
- No changes
- No changes
- 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
QueryOptions
interface that is now used byApolloClient.query
options, instead of the previousWatchQueryOptions
interface. This helps reduce confusion (especially in the docs) that made it look likeApolloClient.query
acceptedApolloClient.watchQuery
only options, likepollingInterval
. (@hwillson in #3569)
- Allow
cache
to be given as a configuration option toApolloBoost
. (@dandean in #3561) - Allow
headers
andcredentials
to be passed in as configuration parameters to theapollo-boost
ApolloClient
constructor. (@rzane in #3098)
- Added optional generics to cache manipulation methods (typescript). (@mvestergaard in #3541)
- 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)
- Store key names generated by
getStoreKeyName
now leverage a more deterministic approach to handling JSON based strings. This prevents store key names from differing when usingargs
like{ prop1: 'value1', prop2: 'value2' }
and{ prop2: 'value2', prop1: 'value1' }
. (@gdi2290 in #2869) - Avoid needless
hasOwnProperty
check indeepFreeze
. (@benjamn in #3545)
- No new changes.
- Fix SSR and
cache-and-network
fetch policy (@dastoori in #3372) - Fixed an issue where the
updateQuery
method passed toObservableQuery.fetchMore
was 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 theprototype
ofthis
manually. (@seklyza in #3306) - Added safeguards to make sure
QueryStore.initQuery
andQueryStore.markQueryResult
don't try to set the network status of afetchMoreForQueryId
query, if it does not exist in the store. This was happening when a query component was unmounted while afetchMore
was still in flight. (@conrad-vanl in #3367, @doomsower in #3469)
- Various internal code cleanup, tooling and dependency changes.
- Various internal code cleanup, tooling and dependency changes.
- 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)
- Make
maybeDeepFreeze
a 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)