apollo-cache-persist
apollo-cache-persist copied to clipboard
chore(deps): update dependency @apollo/client to v3.9.5
This PR contains the following updates:
| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| @apollo/client (source) | 3.7.17 -> 3.9.5 |
Release Notes
apollographql/apollo-client (@apollo/client)
v3.9.5
Patch Changes
-
#11595
8c20955Thanks @phryneas! - Bumps the dependencyrehacktto 0.0.5 -
#11592
1133469Thanks @Stephen2! - StrengthenMockedResponse.newDatatype -
#11579
1ba2fd9Thanks @jerelmiller! - Fix issue where partial data is reported touseQuerywhen usingnotifyOnNetworkStatusChangeafter it errors while another overlapping query succeeds. -
#11579
1ba2fd9Thanks @jerelmiller! - Fix an issue where a partial cache write for an errored query would result in automatically refetching that query. -
#11562
65ab695Thanks @mspiess! - Mocks with an infinite delay no longer require result or error
v3.9.4
Patch Changes
-
#11403
b0c4f3aThanks @jerelmiller! - Fix issue inuseLazyQuerythat results in a double network call when calling the execute function with no arguments after having called it previously with another set of arguments. -
#11576
e855d00Thanks @alessbell! - Revert PR #11202 to fix caching bug reported in #11560
v3.9.3
Patch Changes
-
#11525
dce923aThanks @vezaynk! - Allows passing in client via options to useFragment -
#11558
8cba16fThanks @alessbell! - Fixunbound-methodlinter error on ObservableQuery methods exposed on useQuery's QueryResult object.
v3.9.2
Patch Changes
- #11552
6ac2b0cThanks @jerelmiller! - Fix import inuseLazyRefcausing import issues in the nextjs package.
v3.9.1
Patch Changes
-
#11516
8390feaThanks @phryneas! - Fix an incorrect string substitution in a warning message. -
#11515
c9bf93bThanks @vladar! - Avoid redundant refetchQueries call for mutation with no-cache policy (fixes #10238) -
#11545
84a6beaThanks @alessbell! - Remove error thrown byinFlightLinkObservablesintended to be removed before 3.9 release.
v3.9.0
Minor Changes
Memory optimizations
-
#11424
62f3b6dThanks @phryneas! - Simplify RetryLink, fix potential memory leakHistorically,
RetryLinkwould keep avaluesarray of all previous values, in case the operation would get an additional subscriber at a later point in time.In practice, this could lead to a memory leak (#11393) and did not serve any further purpose, as the resulting observable would only be subscribed to by Apollo Client itself, and only once - it would be wrapped in a
Concastbefore being exposed to the user, and thatConcastwould handle subscribers on its own. -
#11435
5cce53eThanks @phryneas! - DeprecatescanonizeResults.Using
canonizeResultscan result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks. -
#11254
d08970dThanks @benjamn! - DecouplecanonicalStringifyfromObjectCanonfor better time and memory performance. -
#11356
cc4ac7eThanks @phryneas! - Fix a potential memory leak inFragmentRegistry.transformandFragmentRegistry.findFragmentSpreadsthat would hold on to passed-inDocumentNodesfor too long. -
#11370
25e2cb4Thanks @phryneas! -parsefunction: improve memory management- use LRU
WeakCacheinstead ofMapto keep a limited number of parsed results - cache is initiated lazily, only when needed
- expose
parse.resetCache()method
- use LRU
-
#11389
139acd1Thanks @phryneas! -documentTransform: useoptimismandWeakCacheinstead of directly storing data on theTrie -
#11358
7d939f8Thanks @phryneas! - Fixes a potential memory leak inConcastthat might have been triggered whenConcastwas used outside of Apollo Client. -
#11344
bd26676Thanks @phryneas! - Add aresetCachemethod toDocumentTransformand hookInMemoryCache.addTypenameTransformup toInMemoryCache.gc -
#11367
30d17bfThanks @phryneas! -print: useWeakCacheinstead ofWeakMap -
#11387
4dce867Thanks @phryneas! -QueryManager.transformCache: useWeakCacheinstead ofWeakMap -
#11369
2a47164Thanks @phryneas! - Persisted Query Link: improve memory management- use LRU
WeakCacheinstead ofWeakMapto keep a limited number of hash results - hash cache is initiated lazily, only when needed
- expose
persistedLink.resetHashCache()method - reset hash cache if the upstream server reports it doesn't accept persisted queries
- use LRU
-
#10804
221dd99Thanks @phryneas! - use WeakMap in React Native with Hermes -
#11355
7d8e184Thanks @phryneas! - InMemoryCache.gc now also triggers FragmentRegistry.resetCaches (if there is a FragmentRegistry) -
#11409
2e7203bThanks @phryneas! - Adds an experimentalApolloClient.getMemoryInternalshelper -
#11343
776631dThanks @phryneas! - Addresetmethod toprint, hook up toInMemoryCache.gc
Suspense-enabled data fetching on user interaction with useLoadableQuery
-
#11300
a815873Thanks @jerelmiller! - Introduces a newuseLoadableQueryhook. This hook works similarly touseBackgroundQueryin that it returns aqueryRefthat can be used to suspend a component via theuseReadQueryhook. It provides a more ergonomic way to load the query during a user interaction (for example when wanting to preload some data) that would otherwise be clunky withuseBackgroundQuery.function App() { const [loadQuery, queryRef, { refetch, fetchMore, reset }] = useLoadableQuery(query, options); return ( <> <button onClick={() => loadQuery(variables)}>Load query</button> <Suspense fallback={<SuspenseFallback />}> {queryRef && <Child queryRef={queryRef} />} </Suspense> </> ); } function Child({ queryRef }) { const { data } = useReadQuery(queryRef); // ... }
Begin preloading outside of React with createQueryPreloader
- #11412
58db5c3Thanks @jerelmiller! - Add the ability to start preloading a query outside React to begin fetching as early as possible. CallcreateQueryPreloaderto create apreloadQueryfunction which can be called to start fetching a query. This returns aqueryRefwhich is passed touseReadQueryand suspended until the query is done fetching.
Testing utility improvements
-
#11178
4d64a6fThanks @sebakerckhof! - Support re-using of mocks in the MockedProvider -
#6701
8d2b4e1Thanks @prowe! - Ability to dynamically match mocksAdds support for a new property
MockedResponse.variableMatcher: a predicate function that accepts avariablesparam. Iftrue, thevariableswill be passed into theResultFunctionto help dynamically build a response.
New useQueryRefHandlers hook
-
#11412
58db5c3Thanks @jerelmiller! - Create a newuseQueryRefHandlershook that returnsrefetchandfetchMorefunctions for a givenqueryRef. This is useful to get access to handlers for aqueryRefthat was created bycreateQueryPreloaderor when the handlers for aqueryRefproduced by a different component are inaccessible.const MyComponent({ queryRef }) { const { refetch, fetchMore } = useQueryRefHandlers(queryRef); // ... }
Bail out of optimisticResponse updates with the IGNORE sentinel object
-
#11410
07fcf6aThanks @sf-twingate! - Allow returningIGNOREsentinel object fromoptimisticResponsefunctions to bail-out from the optimistic update.Consider this example:
const UPDATE_COMMENT = gql` mutation UpdateComment($commentId: ID!, $commentContent: String!) { updateComment(commentId: $commentId, content: $commentContent) { id __typename content } } `; function CommentPageWithData() { const [mutate] = useMutation(UPDATE_COMMENT); return ( <Comment updateComment={({ commentId, commentContent }) => mutate({ variables: { commentId, commentContent }, optimisticResponse: (vars, { IGNORE }) => { if (commentContent === "foo") { // conditionally bail out of optimistic updates return IGNORE; } return { updateComment: { id: commentId, __typename: "Comment", content: commentContent, }, }; }, }) } /> ); }The
IGNOREsentinel can be destructured from the second parameter in the callback function signature passed tooptimisticResponse.const preloadQuery = createQueryPreloader(client); const queryRef = preloadQuery(QUERY, { variables, ...otherOptions }); function App() { return { <Suspense fallback={<div>Loading</div>}> <MyQuery /> </Suspense> } } function MyQuery() { const { data } = useReadQuery(queryRef); // do something with data }
Network adapters for multipart subscriptions usage with Relay and urql
-
#11301
46ab032Thanks @alessbell! - Add multipart subscription network adapters for Relay and urqlRelay
import { createFetchMultipartSubscription } from "@​apollo/client/utilities/subscriptions/relay"; import { Environment, Network, RecordSource, Store } from "relay-runtime"; const fetchMultipartSubs = createFetchMultipartSubscription( "http://localhost:4000", ); const network = Network.create(fetchQuery, fetchMultipartSubs); export const RelayEnvironment = new Environment({ network, store: new Store(new RecordSource()), });Urql
import { createFetchMultipartSubscription } from "@​apollo/client/utilities/subscriptions/urql"; import { Client, fetchExchange, subscriptionExchange } from "@​urql/core"; const url = "http://localhost:4000"; const multipartSubscriptionForwarder = createFetchMultipartSubscription(url); const client = new Client({ url, exchanges: [ fetchExchange, subscriptionExchange({ forwardSubscription: multipartSubscriptionForwarder, }), ], });
skipPollAttempt callback function
-
#11397
3f7eecbThanks @aditya-kumawat! - Adds a newskipPollAttemptcallback function that's called whenever a refetch attempt occurs while polling. If the function returnstrue, the refetch is skipped and not reattempted until the next poll interval. This will solve the frequent use-case of disabling polling when the window is inactive.useQuery(QUERY, { pollInterval: 1000, skipPollAttempt: () => document.hidden, // or !document.hasFocus() }); // or define it globally new ApolloClient({ defaultOptions: { watchQuery: { skipPollAttempt: () => document.hidden, // or !document.hasFocus() }, }, });
QueryManager.inFlightLinkObservables now uses a strong Trie as an internal data structure
-
#11345
1759066Thanks @phryneas!Warning: requires
@apollo/experimental-nextjs-app-supportupdateIf you are using
@apollo/experimental-nextjs-app-support, you will need to update that to at least 0.5.2, as it accesses this internal data structure.
More Minor Changes
-
#11202
7c2bc08Thanks @benjamn! - PreventQueryInfo#markResultmutation ofresult.dataand return cache data consistently whether complete or incomplete. -
#11442
4b6f2bcThanks @jerelmiller! - Remove the need to callretainfromuseLoadableQuerysinceuseReadQuerywill now retain the query. This means that aqueryRefthat is not consumed byuseReadQuerywithin the givenautoDisposeTimeoutMswill now be auto diposed for you.Thanks to #11412, disposed query refs will be automatically resubscribed to the query when consumed by
useReadQueryafter it has been disposed. -
#11438
6d46ab9Thanks @jerelmiller! - Remove the need to callretainfromuseBackgroundQuerysinceuseReadQuerywill now retain the query. This means that aqueryRefthat is not consumed byuseReadQuerywithin the givenautoDisposeTimeoutMswill now be auto diposed for you.Thanks to #11412, disposed query refs will be automatically resubscribed to the query when consumed by
useReadQueryafter it has been disposed. -
#11175
d6d1491Thanks @phryneas! - To work around issues in React Server Components, especially with bundling for the Next.js "edge" runtime we now use an external package to wrapreactimports instead of importing React directly. -
#11495
1190aa5Thanks @jerelmiller! - Increase the default memory limits forexecuteSelectionSetandexecuteSelectionSetArray.
Patch Changes
-
#11275
3862f9bThanks @phryneas! - Add adefaultContextoption and property onApolloClient, e.g. for keeping track of changing auth tokens or dependency injection.This can be used e.g. in authentication scenarios, where a new token might be generated outside of the link chain and should passed into the link chain.
import { ApolloClient, createHttpLink, InMemoryCache } from "@​apollo/client"; import { setContext } from "@​apollo/client/link/context"; const httpLink = createHttpLink({ uri: "/graphql", }); const authLink = setContext((_, { headers, token }) => { return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "", }, }; }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(), }); // somewhere else in your application function onNewToken(newToken) { // token can now be changed for future requests without need for a global // variable, scoped ref or recreating the client client.defaultContext.token = newToken; } -
#11443
ff5a332Thanks @phryneas! - Adds a deprecation warning to the HOC and render prop APIs.The HOC and render prop APIs have already been deprecated since 2020, but we previously didn't have a
@deprecatedtag in the DocBlocks. -
#11385
d9ca4f0Thanks @phryneas! - ensuredefaultContextis also used for mutations and subscriptions -
#11503
67f62e3Thanks @jerelmiller! - Release changes fromv3.8.10 -
#11078
14edebeThanks @phryneas! - ObservableQuery: prevent reporting results of previous queries if the variables changed since -
#11439
33454f0Thanks @jerelmiller! - Address bundling issue introduced in #11412 where thereact/cacheinternals ended up duplicated in the bundle. This was due to the fact that we had areact/hooksentrypoint that imported these files along with the newly introducedcreateQueryPreloaderfunction, which lived outside of thereact/hooksfolder. -
#11371
ebd8fe2Thanks @phryneas! - Clarify types ofEntityStore.makeCacheKey.
v3.8.10
Patch Changes
-
#11489
abfd02aThanks @gronxb! - FixnetworkStatuswithuseSuspenseQuerynot properly updating to ready state when using acache-and-networkfetch policy that returns data equal to what is already in the cache. -
#11483
6394ddaThanks @pipopotamasu! - Fix cache override warning output
v3.8.9
Patch Changes
-
#11472
afc844dThanks @alessbell! - Fix delay: Infinity when set on a MockResponse passed to Mocked Provider so it indefinitely enters loading state. -
#11464
aac12b2Thanks @jerelmiller! - PreventuseFragmentfrom excessively unsubscribing and resubscribing the fragment with the cache on every render. -
#11449
f40cda4Thanks @phryneas! - Removes refences to the typescript "dom" lib. -
#11470
e293bc9Thanks @phryneas! - Remove an unnecessary check from parseAndCheckHttpResponse.
v3.8.8
Patch Changes
-
#11200
ae5091a21Thanks @jerelmiller! - Enablestrictin tsconfig for the entire project. -
#11332
291aea56bThanks @asvishnyakov! - Add missed reexports of MutationFetchPolicy and RefetchWritePolicy to @apollo/client/core -
#10931
e5acf910eThanks @phryneas! -useMutation: also reset internal state on reset
v3.8.7
Patch Changes
-
#11297
c8c76a522Thanks @jerelmiller! - Add an explicit return type for theuseReadQueryhook calledUseReadQueryResult. Previously the return type of this hook was inferred from the return value. -
#11337
bb1da8349Thanks @phryneas! - #11206 used the TypeScript syntaxinfer X extends Ythat was introduced in TS 4.8. This caused some problems for some users, so we are rolling back to a more backwars-compatible (albeit slightly less performant) type.
v3.8.6
Patch Changes
-
#11291
2be7eafe3Thanks @ArioA! - Fix a bug that allows to only callloadErrorMessageswithout also callingloadDevErrorMessages. -
#11274
b29f000f3Thanks @jerelmiller! - Start the query ref auto dispose timeout after the initial promise has settled. This prevents requests that run longer than the timeout duration from keeping the component suspended indefinitely. -
#11289
b5894dbf0Thanks @phryneas! -MockedProvider: defaultconnectToDevToolstofalsein createdApolloClientinstance.This will prevent the mocked
ApolloClientinstance from trying to connect to the DevTools, which would start asetTimeoutthat might keep running after a test has finished. -
#11206
dd2ce7687Thanks @phryneas! -cache.modify: Less strict types & new dev runtime warnings.
v3.8.5
v3.8.4
Patch Changes
- #11195
9e59b251dThanks @phryneas! - Forinvariant.logetc., error arguments are now serialized correctly in the link to the error page.
v3.8.3
Patch Changes
- #11193
fd2a4cf0cThanks @phryneas! - Call devtools registration after ApolloClient is fully set up.
v3.8.2
Patch Changes
-
#10072
51045c336Thanks @Huulivoide! - Fixes race conditions in useReactiveVar that may prevent updates to the reactive variable from propagating through the hook. -
#11162
d9685f53cThanks @jerelmiller! - Ensures GraphQL errors returned in subscription payloads adhere to theerrorPolicyset inclient.subscribe(...)calls. -
#11134
96492e142Thanks @alessbell! - Use separate type imports in useSuspenseQuery and useBackgroundQuery to workaround SWC compiler issue. -
#11117
6b8198109Thanks @phryneas! - Adds a new devtools registration mechanism and tweaks the mechanism behind the "devtools not found" mechanic. -
#11186
f1d429f32Thanks @jerelmiller! - Fix an issue where race conditions when rapidly switching between variables would sometimes result in the wrongdatareturned from the query. Specifically this occurs when a query is triggered with an initial set of variables (VariablesA), then triggers the same query with another set of variables (VariablesB) but switches back to theVariablesAbefore the response forVariablesBis returned. Previously this would result in the data forVariablesBto be displayed whileVariablesAwas active. The data is forVariablesAis now properly returned. -
#11163
a8a9e11e9Thanks @bignimbus! - Fix typo in error message: "occured" -> "occurred" -
#11180
7d9c481e5Thanks @jerelmiller! - Fixes an issue where refetching fromuseBackgroundQueryviarefetchwith an error after an error was already fetched would get stuck in a loading state.
v3.8.1
Patch Changes
-
#11141
c469b1616Thanks @jerelmiller! - Remove newly exported response iterator helpers that caused problems on some installs where@types/nodewas not available.IMPORTANT
The following exports were added in version 3.8.0 that are removed with this patch.
isAsyncIterableIteratorisBlobisNodeReadableStreamisNodeResponseisReadableStreamisStreamableBlob
v3.8.0
Minor Changes
Fetching with Suspense 🎉
-
#10323
64cb88a4bThanks @jerelmiller! - Add support for React suspense with a newuseSuspenseQueryhook.useSuspenseQueryinitiates a network request and causes the component calling it to suspend while the request is in flight. It can be thought of as a drop-in replacement foruseQuerythat allows you to take advantage of React's concurrent features while fetching during render.Consider a
Dogcomponent that fetches and renders some information about a dog named Mozzarella:View code 🐶
import { Suspense } from "react"; import { gql, TypedDocumentNode, useSuspenseQuery } from "@​apollo/client"; interface Data { dog: { id: string; name: string; }; } interface Variables { name: string; } const GET_DOG_QUERY: TypedDocumentNode<Data, Variables> = gql` query GetDog($name: String) { dog(name: $name) { id name } } `; function App() { return ( <Suspense fallback={<div>Loading...</div>}> <Dog name="Mozzarella" /> </Suspense> ); } function Dog({ name }: { name: string }) { const { data } = useSuspenseQuery(GET_DOG_QUERY, { variables: { name }, }); return <>Name: {data.dog.name}</>; }For a detailed explanation of
useSuspenseQuery, see our fetching with Suspense reference. -
#10755
e3c676debThanks @alessbell! - Feature: addsuseBackgroundQueryanduseReadQueryhooksuseBackgroundQueryinitiates a request for data in a parent component and returns aQueryReferencewhich is used to read the data in a child component viauseReadQuery. If the child component attempts to render before the data can be found in the cache, the child component will suspend until the data is available. On cache updates to watched data, the child component callinguseReadQuerywill re-render with new data but the parent component will not re-render (as it would, for example, if it were usinguseQueryto issue the request).Consider an
Appcomponent that fetches a list of breeds in the background while also fetching and rendering some information about an individual dog, Mozzarella:View code 🐶
function App() { const [queryRef] = useBackgroundQuery(GET_BREEDS_QUERY); return ( <Suspense fallback={<div>Loading...</div>}> <Dog name="Mozzarella" queryRef={queryRef} /> </Suspense> ); } function Dog({ name, queryRef, }: { name: string; queryRef: QueryReference<BreedData>; }) { const { data } = useSuspenseQuery(GET_DOG_QUERY, { variables: { name }, }); return ( <> Name: {data.dog.name} <Suspense fallback={<div>Loading breeds...</div>}> <Breeds queryRef={queryRef} /> </Suspense> </> ); } function Breeds({ queryRef }: { queryRef: QueryReference<BreedData> }) { const { data } = useReadQuery(queryRef); return data.breeds.map(({ characteristics }) => characteristics.map((characteristic) => ( <div key={characteristic}>{characteristic}</div> )) ); }For a detailed explanation of
useBackgroundQueryanduseReadQuery, see our fetching with Suspense reference.
Document transforms 📑
-
#10509
79df2c7baThanks @jerelmiller! - Add the ability to specify custom GraphQL document transforms. These transforms are run before reading data from the cache, before local state is resolved, and before the query document is sent through the link chain.To register a custom document transform, create a transform using the
DocumentTransformclass and pass it to thedocumentTransformoption onApolloClient.import { DocumentTransform } from "@​apollo/client"; const documentTransform = new DocumentTransform((document) => { // do something with `document` return transformedDocument; }); const client = new ApolloClient({ documentTransform: documentTransform });For more information on the behavior and API of
DocumentTransform, see its reference page in our documentation.
New removeTypenameFromVariables link 🔗
-
#10853
300957960Thanks @jerelmiller! - Introduce the newremoveTypenameFromVariableslink. This link will automatically remove__typenamefields fromvariablesfor all operations. This link can be configured to exclude JSON-scalars for scalars that utilize__typename.This change undoes some work from #10724 where
__typenamewas automatically stripped for all operations with no configuration. This was determined to be a breaking change and therefore moved into this link.For a detailed explanation of
removeTypenameFromVariables, see its API reference.
New skipToken sentinel ⏭️
-
#11112
b4aefcfe9Thanks @jerelmiller! - Adds support for askipTokensentinel that can be used asoptionsinuseSuspenseQueryanduseBackgroundQueryto skip execution of a query. This works identically to theskipoption but is more type-safe and as such, becomes the recommended way to skip query execution. As such, theskipoption has been deprecated in favor ofskipToken.We are considering the removal of the
skipoption fromuseSuspenseQueryanduseBackgroundQueryin the next major. We are releasing with it now to make migration fromuseQueryeasier and makeskipTokenmore discoverable.useSuspenseQueryimport { skipToken, useSuspenseQuery } from "@​apollo/client"; const id: number | undefined; const { data } = useSuspenseQuery( query, id ? { variables: { id } } : skipToken );useBackgroundQueryimport { skipToken, useBackgroundQuery } from "@​apollo/client"; function Parent() { const [queryRef] = useBackgroundQuery( query, id ? { variables: { id } } : skipToken ); return queryRef ? <Child queryRef={queryRef} /> : null; } function Child({ queryRef }: { queryRef: QueryReference<TData> }) { const { data } = useReadQuery(queryRef); }For a detailed explanation of
skipToken, see its API reference.
New error extraction mechanism, smaller bundles 📉
-
#10887
f8c0b965dThanks @phryneas! - Add a new mechanism for Error Extraction to reduce bundle size by including error message texts on an opt-in basis.By default, errors will link to an error page with the entire error message. This replaces "development" and "production" errors and works without additional bundler configuration.
Bundling the text of error messages and development warnings can be enabled as follows:
import { loadErrorMessages, loadDevMessages } from "@​apollo/client/dev"; if (process.env.NODE_ENV !== "production") { loadErrorMessages(); loadDevMessages(); }For a detailed explanation, see our reference on reducing bundle size.
New @nonreactive directive 🎬
-
#10722
c7e60f83dThanks @benjamn! - Implement a@nonreactivedirective for selectively skipping reactive comparisons of query result subtrees.The
@nonreactivedirective can be used to mark query fields or fragment spreads and is used to indicate that changes to the data contained within the subtrees marked@nonreactiveshould not trigger re-rendering. This allows parent components to fetch data to be rendered by their children without re-rendering themselves when the data corresponding with fields marked as@nonreactivechange.Consider an
Appcomponent that fetches and renders a list of ski trails:View code 🎿
const TrailFragment = gql` fragment TrailFragment on Trail { name status } `; const ALL_TRAILS = gql` query allTrails { allTrails { id ...TrailFragment @​nonreactive } } ${TrailFragment} `; function App() { const { data, loading } = useQuery(ALL_TRAILS); return ( <main> <h2>Ski Trails</h2> <ul> {data?.trails.map((trail) => ( <Trail key={trail.id} id={trail.id} /> ))} </ul> </main> ); }The
Trailcomponent renders a trail's name and status and allows the user to execute a mutation to toggle the status of the trail between"OPEN"and"CLOSED":View code 🎿
const Trail = ({ id }) => { const [updateTrail] = useMutation(UPDATE_TRAIL); const { data } = useFragment({ fragment: TrailFragment, from: { __typename: "Trail", id, }, }); return ( <li key={id}> {data.name} - {data.status} <input checked={data.status === "OPEN" ? true : false} type="checkbox" onChange={(e) => { updateTrail({ variables: { trailId: id, status: e.target.checked ? "OPEN" : "CLOSED", }, }); }} /> </li> ); };Notice that the
Trailcomponent isn't receiving the entiretrailobject via props, only theidwhich is used along with the fragment document to create a live binding for each trail item in the cache. This allows eachTrailcomponent to react to the cache updates for a single trail independently. Updates to a trail'sstatuswill not cause the parentAppcomponent to rerender since the@nonreactivedirective is applied to theTrailFragmentspread, a fragment that includes thestatusfield.For a detailed explanation, see our
@nonreactivereference and @alessbell's post on the Apollo blog about using@nonreactivewithuseFragment.
Abort the AbortController signal more granularly 🛑
-
#11040
125ef5b2aThanks @phryneas! -HttpLink/BatchHttpLink: Abort theAbortControllersignal more granularly.Before this change, when
HttpLink/BatchHttpLinkcreated anAbortControllerinternally, the signal would always be.aborted after the request was completed. This could cause issues with Sentry Session Replay and Next.js App Router Cache invalidations, which just replayed the fetch with the same options - including the cancelledAbortSignal.With this change, the
AbortControllerwill only be.abort()ed by outside events, not as a consequence of the request completing.
useFragment drops its experimental label 🎓
-
#10916
ea75e18deThanks @alessbell! - Remove experimental labels.useFragment, introduced in3.7.0asuseFragment_experimental, is no longer an experimental API 🎉 We've removed the_experimentalsuffix from its named export and have made a number of improvements.For a detailed explanation, see our
useFragmentreference and @alessbell's post on the Apollo blog about usinguseFragmentwith@nonreactivefor improved performance when rendering lists.useFragmentimprovements-
#10765
35f36c5aaThanks @phryneas! - More robust types for thedataproperty onUseFragmentResult. When a partial result is given, the type is now correctly set toPartial<TData>. -
#11083
f766e8305Thanks @phryneas! - Adjust the rerender timing ofuseQueryto more closely align withuseFragment. This means that cache updates delivered to both hooks should trigger renders at relatively the same time. Previously, theuseFragmentmight rerender much faster leading to some confusion. -
#10836
6794893c2Thanks @phryneas! - Remove the deprecatedreturnPartialDataoption fromuseFragmenthook.
-
More Minor Changes
-
#10895
e187866fdThanks @Gelio! - Add generic type parameter for the entity modified incache.modify. Improves TypeScript type inference for that type's fields and values of those fields.Example:
cache.modify<Book>({ id: cache.identify(someBook), fields: { title: (title) => { // title has type `string`. // It used to be `any`. }, => { // author has type `Reference | Book["author"]`. // It used to be `any`. }, }, }); -
#10895
e187866fdThanks @Gelio! - Use unique opaque types for theDELETEandINVALIDATEApollo cache modifiers.This increases type safety, since these 2 modifiers no longer have the
anytype. Moreover, it no longer triggers the@typescript-eslint/no-unsafe-returnrule. -
#10340
4f73c5ca1Thanks @alessbell! - Avoid callinguseQueryonCompletedfor cache writes -
#10527
0cc7e2e19Thanks @phryneas! - Remove thequery/mutation/subscriptionoption from hooks that already take that value as their first argument. -
#10506
2dc2e1d4fThanks @phryneas! - prevent accidental widening of inferredTDataandTVariablesgenerics for query hook option arguments -
#10521 [
fbf729414](https://togithub.com/apollographql/apollo-cl
Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about these updates again.
- [ ] If you want to rebase/retry this PR, check this box
This PR has been generated by Mend Renovate. View repository job log here.