Skip to content

fix(deps): update apollo graphql packages (major) - #88

Open
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/major-apollo-graphql-packages
Open

renovate[bot] wants to merge 1 commit into
mainfrom
renovate/major-apollo-graphql-packages

Conversation

@renovate

@renovate renovate Bot commented Jul 16, 2021

Copy link
Copy Markdown

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
@apollo/client (source) 3.5.54.3.1 age confidence
apollo-server-express (source) 2.25.33.13.0 age confidence

Release Notes

apollographql/apollo-client (@​apollo/client)

v4.3.1

Compare Source

Patch Changes
  • #​13464 37f700e Thanks @​jerelmiller! - Fix an issue where useLazyQuery did not rerender with new variables until the network request had completed when calling execute with new variables while a request was already in-flight.

v4.3.0

Compare Source

Minor Changes
  • #​13447 24133fe Thanks @​jerelmiller! - Field policies and inputObjects can now tell the cache whether a field is a list of scalars or a scalar whose value is an array. Previously all arrays were iterated and only the inner type was provided to the scalar parse/serialize functions.

    This required some breaking changes from previous prerelease versions:

    • The field policy scalar option and inputObjects type string now use GraphQL list syntax to mark a field as a list of scalars
    • The abstract cache.getScalarForField is now cache.getScalarTypeForField and is expected to return the string representing the scalar type rather than the Scalar instance
    new InMemoryCache({
      scalars: {
        DateTime: new Scalar(/*...*/),
      },
      inputObjects: {
        EventFilter: {
          fields: {
            // Previously only the scalar type was provided
            datesBefore: "DateTime",
    
            // List syntax now required
            datesAfter: "[DateTime]",
            dates2d: "[[DateTime]]",
          },
        },
      },
      typePolicies: {
        Event: {
          fields: {
            // Previously only the scalar type was provided
            datesBefore: {
              scalar: "DateTime",
            },
    
            // List syntax now required
            datesAfter: {
              scalar: "[DateTime]",
            },
            dates2d: {
              scalar: "[[DateTime]]",
            },
          },
        },
      },
    });

    Now it's possible to handle scalars that are represented by arrays:

    const dateTimeRangeScalar = new Scalar<
      [string, string],
      { start: Date; end: Date }
    >({
      parse: ([start, end]) => ({
        start: new Date(start),
        end: new Date(end),
      }),
      serialize: (range) => [range.start.toISOString(), range.end.toISOString()],
      is: (value) => !Array.isArray(value),
    });
    
    const cache = new InMemoryCache({
      scalars: {
        DateTimeRange: dateTimeRangeScalar,
      },
      typePolicies: {
        Event: {
          fields: {
            range: {
              scalar: "DateTimeRange",
            },
          },
        },
      },
    });
    
    const query = gql`
      query {
        event {
          range
        }
      }
    `;
    
    cache.writeQuery({
      query,
      data: {
        event: {
          __typename: "Event",
          // Server returns DateTimeRange as a JSON array
          range: ["2024-01-01T00:00:00Z", "2024-06-01T00:00:00Z"],
        },
      },
    });
    
    const { data } = useQuery(query);
    // => { event: { __typename: "Event", range: { start: Date, end: Date } } }
  • #​13324 0abd8de Thanks @​jerelmiller! - Fix the accuracy of dataState in complex incremental streaming scenarios, especially when combined with returnPartialData: true.

    Prior to this change, all intermediate chunks used for both @defer and @stream directives returned a dataState of streaming, regardless of whether the actual data shape fit the definition of the streaming data state. The streaming data state represents an incomplete incremental response where the only holes in the data occur at @defer boundaries.

    Let's use the following example of where the previous dataState fell down when combined with returnPartialData.

    query GreetingQuery {
      greeting {
        message
        ... @defer {
          recipient {
            name
            email
          }
        }
      }
    }
    1. Scenario 1: partial data inside a @defer boundary written to the cache

    Let's say the cache contained the following partial data:

    {
      greeting: {
        __typename: "Greeting",
        recipient: {
          __typename: "Person",
          name: "John Doe",
        },
      },
    };

    After the first chunk arrives from the server, the data looks like the following:

    {
      greeting: {
        __typename: "Greeting",
        message: "Hello, John",
        recipient: {
          __typename: "Person",
          name: "John Doe",
        },
      },
    };

    This data is not complete because recipient.email is missing. This data is also not streaming because the data requirements in the @defer boundary are partially fulfilled due to the existence of recipient. This could lead to runtime crashes on recipient.email if you use the existence of recipient to detect whether data in the @defer boundary has streamed in or not. This change now accurately reports this as partial to ensure the field is marked as a partial field in recipient.

    1. Scenario 2: partial data written to the cache that fulfills the data requirements of the @defer boundary

    Let's say the cache contained the following partial data:

    {
      greeting: {
        __typename: "Greeting",
        recipient: {
          __typename: "Person",
          name: "John Doe",
          email: "john@example.com",
        },
      },
    };

    After the first chunk arrives from the server, the data looks like the following:

    {
      greeting: {
        __typename: "Greeting",
        message: "Hello, John",
        recipient: {
          __typename: "Person",
          name: "John Doe",
          email: "john@example.com",
        },
      },
    };

    In this case, the combination of the first chunk and the partial data in the cache now fulfills the data requirements of the query. Even though the server is still streaming data (NetworkStatus.streaming), we can report this as dataState: "complete" since it is safe to access data on all fields.

    This change also means @stream queries by definition fulfill the data requirements of the query after the first chunk arrives since @stream operates on lists and contains no data holes. @stream queries now accurately report dataState as complete or partial, depending on whether the list mixes partial data with streamed list items.

    As a result of this change, some cases where you'd previously see dataState reported as "streaming" are now reported as partial or complete.

    If you use dataState to determine whether an incremental request is still in-flight, please use networkStatus instead to check for NetworkStatus.streaming. dataState is type narrowing feature and not intended to report the network status.

  • #​13274 7b10078 Thanks @​jerelmiller! - Adds Scalar.fromGraphQLScalarType helper to create a Scalar instance from an existing graphql.js GraphQLScalarType.

    import { GraphQLScalarType } from "graphql";
    import { Scalar } from "@apollo/client";
    
    const dateTimeScalarType = new GraphQLScalarType<Date, string>({
      // ...
    });
    
    const dateTimeScalar = Scalar.fromGraphQLScalarType(dateTimeScalarType, {
      is: (value) => value instanceof Date,
    });
  • #​13421 d6197a4 Thanks @​jerelmiller! - The minimum supported TypeScript version is now 5.9.x.

  • #​13270 d080f11 Thanks @​jerelmiller! - Adds the plumbing and types implementation for declaring custom scalars and configuring custom scalars in InMemoryCache.

    You can declare custom scalar types with declaration merging on the ApolloCache.Scalars interface:

    // apollo.d.ts
    import "@apollo/client";
    
    declare module "@apollo/client" {
      namespace ApolloCache {
        interface Scalars {
          Date: { serialized: string; parsed: Date };
        }
      }
    }

    This enables the scalars option in InMemoryCache:

    import { Scalar } from "@apollo/client";
    
    const cache = new InMemoryCache({
      scalars: {
        Date: new Scalar({
          parse: (dateString) => new Date(dateString),
          serialize: (date) => date.toISOString(),
          is: (value) => value instanceof Date,
        }),
      },
    });
  • #​13250 bad7035 Thanks @​jerelmiller! - Add the ability to define the cache type for the client. client.cache currently returns ApolloCache as the cache type regardless of what cache you've provided to ApolloClient.

    Declare the cache type using the cache property in the TypeOverrides interface to set the cache implementation used for the client.

    // apollo.d.ts
    import type { InMemoryCache } from "@apollo/client";
    
    declare module "@apollo/client" {
      export interface TypeOverrides {
        cache: InMemoryCache;
      }
    }

    Now anywhere cache is accessible, the type is the declared cache type:

    client.cache;
    //     ^? InMemoryCache
    
    client.mutate({
      update: (cache) => {
        //     ^? InMemoryCache
      },
    });

    [!NOTE]
    Setting a cache type enforces that cache type in the cache option for the ApolloClient constructor.

  • #​13406 bd74ccb Thanks @​jerelmiller! - Emit a development-only warning when a feud is detected between queries that overwrite each other's data. This should make it easier to detect when you need to select a key field or add a merge function to a field policy.

  • #​13390 90e338c Thanks @​jerelmiller! - Fix issue where sibling @defer fragments were pruned incorrectly when at least one of the @defer fragments wasn't delivered.

    As a result of this change, a label argument is now added to all outgoing @defer directives when using the GraphQL17Alpha9Handler in order to disambiguate the @defer fragments from each other.

  • #​13426 a9beaff Thanks @​jerelmiller! - Version bump only to rc.

  • #​13416 f2d5d5a Thanks @​jerelmiller! - Add GraphQLCodegenIncremental type overrides that assemble GraphQL Codegen @defer operation types when dataState is "complete".

  • #​13372 e4cde69 Thanks @​jerelmiller! - Parse scalar fields for no-cache queries.

  • #​13386 0be8fd8 Thanks @​atharv-sys32! - Support skipToken with useSubscription to provide a more type-safe way to skip subscription execution with required variables.

    import { skipToken, useSubscription } from "@apollo/client/react";
    
    // Use `skipToken` in place of `skip: true` for better type safety
    // for required variables
    const { data } = useSubscription(
      SUBSCRIPTION,
      id ? { variables: { id } } : skipToken
    );
  • #​13337 2df711f Thanks @​jcostello-atlassian! - Allow overriding the from input of useFragment, useSuspenseFragment, readFragment, writeFragment and related fragment APIs via a new FromOptionValue key on the TypeOverrides interface.

    By default, from continues to accept StoreObject | Reference | FragmentType<TData> | string. Apps can now supply a stricter policy (for example, requiring __typename and disallowing nullish identifier values) without affecting StoreObject, cache.identify, cache.modify or optimistic writes.

    // apollo.d.ts
    import "@apollo/client";
    import type { HKT, StoreValue } from "@apollo/client/utilities";
    
    type StrictFrom<TData extends { __typename: string }> =
      | {
          // the `__typename` has to match the one of the fragment type
          __typename: TData["__typename"];
          // `& {}` forces values to be "defined" so an explicit `undefined`
          // (as well as `null`) is rejected.
          [key: string]: Exclude<StoreValue, null | undefined> & {};
        }
      | { __ref: string }
      | string
      | null;
    
    interface StrictFromHKT extends HKT {
      arg1: { __typename: string }; // TData
      return: StrictFrom<this["arg1"]>;
    }
    
    declare module "@apollo/client" {
      export interface TypeOverrides {
        FromOptionValue: StrictFromHKT;
      }
    }
  • #​13405 f923ab4 Thanks @​jerelmiller! - Field policy read and merge functions are now ignored when the field policy configures the scalar option. If a read or merge function is provided alongside scalar, a development-only warning is emitted.

  • #​13393 434d25f Thanks @​jerelmiller! - Change when @defer fragments and @stream fields are pruned for cache-first and cache-and-network fetch policies to better match the network when the initial value contained a partial result:

    • cache-first: prune undelivered @defer fragments or @stream items when the result is fetched from the network due to a partial result
    • cache-and-network: prune undelivered @defer fragments or @stream items if the initial cache value was partial. If the first value emitted from the cache is complete, the results will not be pruned.

    This makes the emitted results more predictable by following what the network has delivered and avoids some ambiguity in other edge cases.

    For example, with a cache-first fetch policy where all @defer fields are written to the cache, but a non-deferred field is partial, the values emitted from the client previously looked like the following:

    query {
      user {
        id
        name
        ... @defer {
          email
        }
      }
    }
    // data written to the cache is missing name
    { user: { id: 1, email: "user.cache@example.com" }}
    
    // 1. empty because the result is partial
    { data: undefined, dataState: "empty", ... }
    // 2. returns all data because the cache contains a value for email
    { data: { user: 1, name: "User", email: "user.cache@example.com" }, dataState: "complete" }
    // 3. email updated from the server
    { data: { user: 1, name: "User", email: "user.network@example.com" }, dataState: "complete" }

    Here the result is confusing because the initial value returned from the query was undefined, yet a complete result was returned after the initial chunk from the network returned (which did not contain email).

    The cache values are now pruned if the network hasn't delivered them yet:

    // 1. empty because the result is partial
    { data: undefined, dataState: "empty" }
    // 2. email hasn't been delivered by the network so it gets pruned
    { data: { user: 1, name: "User" }, dataState: "streaming" }
    // 3. full result returned after the network streams the email field
    { data: { user: 1, name: "User", email: "user.network@example.com" }, dataState: "complete" }

    This is especially helpful in situations where @defer boundaries that are never delivered due to errors prevent an awkward situation where the client would otherwise have to choose whether to serve the stale cache result from the cache, or prune the undelivered fragment on the final chunk.

  • #​13270 6031987 Thanks @​jerelmiller! - Adds a scalar option to InMemoryCache field policies that tells the cache which scalar to use when parsing or serializing the field value.

    import { Scalar } from "@apollo/client";
    
    new InMemoryCache({
      scalars: {
        DateTime: new Scalar({
          parse: (dateString) => new Date(dateString),
          serialize: (date) => date.toISOString(),
        }),
      },
      typePolicies: {
        Event: {
          fields: {
            startTime: {
              // Parse this field using the DateTime scalar
              scalar: "DateTime",
            },
          },
        },
      },
    });

    This scalar definition is now used to properly parse or serialize the field value for cache reads and writes as well as cache.extract() and cache.restore().

  • #​13273 0886de1 Thanks @​jerelmiller! - Automatically serialize variables that include custom scalar values. This includes cache reads and writes as well as requests to the network.

    For more complex input objects, a new inputObjects option is available to InMemoryCache that specifies where nested scalar fields are found.

    const cache = new InMemoryCache({
      scalars: {
        DateTime: new Scalar({
          parse: (value) => new Date(value),
          serialize: (value) => value.toISOString(),
          is: (value) => value instanceof Date,
        }),
      },
      inputObjects: {
        EventFilter: {
          fields: {
            date: "DateTime",
          },
        },
      },
    });
    
    const client = new ApolloClient({ cache, link });
    
    await client.query({
      query: gql`
        query Event($filter: EventFilter!) {
          event(filter: $filter) {
            name
          }
        }
      `,
      variables: {
        filter: {
          date: new Date("2026-01-01T00:00:00.000Z"),
        },
      },
    });
    
    // The link receives:
    // { filter: { date: "2026-01-01T00:00:00.000Z" } }
  • #​13424 d2bca2e Thanks @​jerelmiller! - Remove the custom NoInfer type utility in favor of the native NoInfer introduced in TypeScript 5.4.

  • #​13270 d080f11 Thanks @​jerelmiller! - Adds the getScalar abstract method to ApolloCache that cache subclasses override to provide scalar behavior to Apollo Client. Defaults to unconditionally return undefined if not specified.

  • #​13406 bd74ccb Thanks @​jerelmiller! - Fixes an issue where cache feuds between queries selecting incompatible non-normalized data could return untransformed network values.

    Apollo Client now always writes network results to the cache before delivering them, ensuring custom scalars and field read functions are applied. To prevent repeated refetches when competing queries repeatedly make each other's cache results incomplete, Apollo Client stops automatically refetching a query after it sees the same incomplete result again.

    This may add one network request in these cache-feud scenarios.

Patch Changes
  • #​13408 7a5164d Thanks @​jerelmiller! - Fix dataState to report "streaming" instead of "partial" when returnPartialData is true and the cache result is missing only @defer fields.

  • #​13381 9c73762 Thanks @​jerelmiller! - Fix an issue where a network-only query leaked partial cache data for @defer fragments that were not delivered by the network due to an error that bubbled to the @defer fragment boundary.

  • #​13390 90e338c Thanks @​jerelmiller! - Fix an issue where a sibling non-deferred fragment might be accidentally pruned when the @defer fragment hadn't been delivered.

  • #​13442 ed033d4 Thanks @​jerelmiller! - Remove the optional modifier from the variables property provided to the update function in client.mutate and useMutation. variables is always a defined object, even when variables are not provided to the mutation.

  • #​13324 0abd8de Thanks @​jerelmiller! - Fix an issue where field read functions were not applied to intermediate results while streaming @defer responses. cache.diff ran the read functions, but the transformed values were only applied to the emitted result when the updated cache result was considered complete. Intermediate chunks whose only holes were at @defer boundaries now correctly return the result of field read functions.

    new InMemoryCache({
      typePolicies: {
        Greeting: {
          fields: {
            message: {
              read: (message) => message.toUpperCase(),
            },
          },
        },
      },
    });
    
    // query GreetingQuery {
    //   greeting {
    //     message
    //     ... @defer {
    //       recipient { name }
    //     }
    //   }
    // }
    
    // First chunk previously returned:
    // { greeting: { message: "Hello world" } }
    //
    // Now correctly returns while still streaming:
    // { greeting: { message: "HELLO WORLD" } }
  • #​13403 aaff7a8 Thanks @​jerelmiller! - Fix issue where the wrong dataState was returned when there was nothing written to the cache and a @defer fragment was marked pending.

  • #​13347 7d543d6 Thanks @​jerelmiller! - Fix an issue where network-only incremental queries could cause cache data to leak into the emitted result when a @defer or @stream boundary already had complete data in the cache. Cache data inside pending @defer objects and @stream arrays are now pruned so that only completed @defer or @stream boundaries are returned.

    NOTE: This change only applies to InMemoryCache when using GraphQL17Alpha9Handler.

  • #​13329 1d581d2 Thanks @​AmariahAK! - Cache diffs for incomplete queries no longer pay the cost of building a full MissingFieldError when the missing property is not accessed. The error object is now only constructed when the missing property is accessed the first time. This improves performance by avoiding a V8 stack capture when missing is ignored entirely.

    As an additional small performance improvement, JSON.stringify is no longer used in the error message on objects whose cache ID is known. JSON.stringify is only used for non-normalized objects.

  • #​13381 9c73762 Thanks @​jerelmiller! - Fix an issue where a @defer query reported the dataState as complete instead of streaming when an error occurs on a deferred field that bubbled to the defer boundary.

  • #​13324 0abd8de Thanks @​jerelmiller! - Fix an issue with @stream queries when using returnPartialData: true where the streamed list was truncated after the first incremental chunk when the list contained partial cache data. The list is no longer truncated and partial list items are now retained as incremental chunks arrive. The dataState is now reported as partial until the server has streamed enough of the list so that each list item fully satisfies the query.

    This change also updates @stream queries so that they reported with dataState: "complete instead of "streaming" since it is safe to access all fields in the response.

  • #​13373 2551937 Thanks @​jerelmiller! - Fix an issue where a cache write in the middle of polling would remain as the query value if future poll requests returned deep equal results to previous polling results.

  • #​13448 77e1e35 Thanks @​jerelmiller! - Mark skip as deprecated in useQuery and useSubscription now that both of these hooks support skipToken.

  • #​13403 aaff7a8 Thanks @​jerelmiller! - Fix issue where setting returnPartialData: true might report the wrong dataState when partial data was written to the cache and @defer fragments were pending.

  • #​13347 7d543d6 Thanks @​jerelmiller! - Fix an issue where partial cache data could leak into intermediate incremental results. This could cause runtime crashes if you relied on the presence of values to determine whether the @defer data had streamed in or not.

  • #​13381 9c73762 Thanks @​jerelmiller! - Fix an invariant error thrown when a @defer boundary received a payload after it had already been marked complete.

  • #​13268 419e2b5 Thanks @​DaleSeo! - Align the remaining cache generic constraints with Cache.Implementation. The deprecated React mutation types (MutationHookOptions, MutationFunctionOptions, MutationTuple) and the internal InternalRefetchQueriesOptions and QueryInfo types still constrained their cache type parameter to ApolloCache, so they now match the rest of the overridable cache API.

v4.2.12

Compare Source

Patch Changes

v4.2.11

Compare Source

Patch Changes
  • #​13398 3dd3e9a Thanks @​phryneas! - Fix type signature of some DocumentationTypes to fix their display in our documentation.

  • #​13392 d4f0771 Thanks @​jerelmiller! - Add a development-only warning when a network result is written to the cache but reading the query back from the cache returns a partial result. This usually points at a merge or read function that did not repair missing fields in the cache, which prevents Apollo Client from applying the cache result to the data received by the network.

v4.2.10

Compare Source

Patch Changes
  • #​13385 bfb674e Thanks @​jerelmiller! - Fix accidental widening of the client.mutate return type when optimisticResponse was present.

  • #​13382 365373e Thanks @​jerelmiller! - Fix result types widened when a query's variables had constant types (e.g. TypedDocumentNode<Data, { type: "main" }>). This caused options such as returnPartialData or errorPolicy to be reported as their widened types (e.g. boolean, ErrorPolicy) instead of the value that was passed which returned the wrong data and dataState types.

  • #​13382 365373e Thanks @​jerelmiller! - Fix issue where unknown options were permitted by TypeScript when passed alongside a valid option to APIs with modern signatures.

  • #​13383 5840f50 Thanks @​jerelmiller! - Update the return type of refetch, fetchMore and useLazyQuery's execute function on the provided errorPolicy. Previously these APIs all used the default type which typed data as TData | undefined and error as ErrorLike | undefined.

v4.2.9

Compare Source

Patch Changes
  • #​13364 2f383e7 Thanks @​atharv-sys32! - Fix a bug where GraphQL variable default values were not applied during cache reads when variables with defaults were explicitly set to undefined. This caused @include/@skip directives to throw "Invalid variable referenced" errors when the variable was passed as undefined instead of being omitted entirely.

  • #​13367 2b39cc8 Thanks @​jerelmiller! - Fix an issue where some @export queries would not react to cache updates when the fields keyed by exported variables were updated.

v4.2.8

Compare Source

Patch Changes
  • #​13349 501a33b Thanks @​jerelmiller! - Prevent the setTimeout in connectToDevtools that shows the devtools suggestion from firing when the user agent does not match Chrome or Firefox. This check was previously done inside the setTimeout which meant the timer was scheduled for environments where we'd never show the message anyways. For test environments, this could cause flaky tests when that setTimeout outlived the tests and ran after any virtual DOM was torn down and removed.

v4.2.7

Compare Source

Patch Changes

v4.2.6

Compare Source

Patch Changes
  • #​13315 a406cc9 Thanks @​fallintoplace! - Prevent relay multipart subscriptions from issuing a fetch request after serializing the request body fails.

  • #​13307 abd0781 Thanks @​wolfie! - Speed up cache writes by avoiding a full AST visit of every written field to detect @stream. The check now runs only when the result carries stream info, and only inspects the field node's own directives. As a result, fields that merely contain @stream on a nested field are no longer treated as streamed themselves and now overwrite existing lists like regular fields instead of merging chunk-wise.

v4.2.5

Compare Source

Patch Changes

v4.2.4

Compare Source

Patch Changes
  • #​13281 e4df809 Thanks @​jerelmiller! - Fixes an issue where client.readFragment and client.readQuery ignored the optimistic option when passed in the options object.

v4.2.3

Compare Source

Patch Changes

v4.2.2

Compare Source

Patch Changes

v4.2.1

Compare Source

Patch Changes

v4.2.0

Compare Source

Minor Changes
  • #​13132 f3ce805 Thanks @​phryneas! - Introduce "classic" and "modern" method and hook signatures.

    Apollo Client 4.2 introduces two signature styles for methods and hooks. All signatures previously present are now "classic" signatures, and a new set of "modern" signatures are added alongside them.

    Classic signatures are the default and are identical to the signatures before Apollo Client 4.2, preserving backward compatibility. Classic signatures still work with manually specified TypeScript generics (e.g., useSuspenseQuery<MyData>(...)). However, manually specifying generics has been discouraged for a long time—instead, we recommend using TypedDocumentNode to automatically infer types, which provides more accurate results without any manual annotations.

    Modern signatures automatically incorporate your declared defaultOptions into return types, providing more accurate types. Modern signatures infer types from the document node and do not support manually passing generic type arguments; TypeScript will produce a type error if you attempt to do so.

    Methods and hooks automatically switch to modern signatures the moment any non-optional property is declared in DeclareDefaultOptions. The switch happens across all methods and hooks globally:

    // apollo.d.ts
    import "@apollo/client";
    declare module "@apollo/client" {
      namespace ApolloClient {
        namespace DeclareDefaultOptions {
          interface WatchQuery {
            errorPolicy: "all"; // non-optional → modern signatures activated automatically
          }
        }
      }
    }

    Users can also manually switch to modern signatures without declaring any defaultOptions, for example when wanting accurate type inference without relying on global defaultOptions:

    // apollo.d.ts
    import "@apollo/client";
    declare module "@apollo/client" {
      export interface TypeOverrides {
        signatureStyle: "modern";
      }
    }

    Users can do a global DeclareDefaultOptions type augmentation and then manually switch back to "classic" for migration purposes:

    // apollo.d.ts
    import "@apollo/client";
    declare module "@apollo/client" {
      export interface TypeOverrides {
        signatureStyle: "classic";
      }
    }

    Note that this is not recommended for long-term use. When combined with DeclareDefaultOptions, switching back to classic results in the same incorrect types as before Apollo Client 4.2—methods and hooks will not reflect the defaultOptions you've declared.

  • #​13130 dd12231 Thanks @​jerelmiller! - Improve the accuracy of client.query return type to better detect the current errorPolicy. The data property is no longer nullable when the errorPolicy is none. This makes it possible to remove the undefined checks or optional chaining in most cases.

  • #​13210 1f9a428 Thanks @​jerelmiller! - Add support for automatic event-based refetching, such as window focus.

    The RefetchEventManager class handles automatic refetches in response to events. Apollo Client provides built-in sources for window focus and network reconnect as windowFocusSource and onlineSource.

    Event refetching is fully opt-in. Create and pass a RefetchEventManager instance to the ApolloClient constructor to activate the event listeners.

    import {
      ApolloClient,
      InMemoryCache,
      RefetchEventManager,
      windowFocusSource,
      onlineSource,
    } from "@apollo/client";
    
    const client = new ApolloClient({
      link,
      cache: new InMemoryCache(),
      refetchEventManager: new RefetchEventManager({
        sources: {
          // Refetch when window is focused
          windowFocus: windowFocusSource,
    
          // Refetch when the user comes back online
          online: onlineSource,
        },
      }),
    });

    By default, all active queries refetch when the events fire. Queries can opt out per-event or disable all event refetches:

    // Skip refetch on window focus for this query, but keep `online`
    useQuery(QUERY, {
      refetchOn: { windowFocus: false },
    });
    
    // Disable all event-driven refetches for this query
    useQuery(OTHER_QUERY, {
      refetchOn: false,
    });
    
    // Enable every event for this query, regardless of defaultOptions
    useQuery(LIVE_DASHBOARD, {
      refetchOn: true,
    });
    
    // Dynamically enable or disable a refetch when the event fires
    useQuery(LIVE_DASHBOARD, {
      refetchOn: ({ source, payload }) => {
        if (source === "windowFocus") {
          // payload is the data associated with the event
          return someCondition(payload);
        }
    
        return true;
      },
    });
    
    // Dynamically enable or disable a refetch for a specific event
    useQuery(LIVE_DASHBOARD, {
      refetchOn: {
        windowFocus: ({ payload }) => {
          // payload is the data associated with the event
          return someCondition(payload);
        },
      },
    });

    To enable per-query opt-in rather than opt-out, set defaultOptions.watchQuery.refetchOn to false and enable it per-query instead.

    const client = new ApolloClient({
      link,
      cache,
      refetchEventManager: new RefetchEventManager({
        sources: { windowFocus: windowFocusSource },
      }),
      defaultOptions: {
        watchQuery: { refetchOn: false },
      },
    });
    
    // Only this query refetches on window focus
    useQuery(DASHBOARD_QUERY, { refetchOn: { windowFocus: true } });

    When defaultOptions.watchQuery.refetchOn and per-query refetchOn options are provided, the objects are merged together.

Custom events

You can also add your own custom events that trigger refetches. Register your event name and payload type using TypeScript module augmentation, then provide a source function that returns an Observable. The source's emitted value becomes the event's payload.

import { Observable } from "@apollo/client";
import { filter } from "rxjs";
import { AppState, AppStateStatus, Platform } from "react-native";

declare module "@apollo/client" {
  interface RefetchEvents {
    reactNativeAppStatus: AppStateStatus;
  }
}

const refetchEventManager = new RefetchEventManager({
  sources: {
    reactNativeAppStatus: () => {
      return new Observable((observer) => {
        const subscription = AppState.addEventListener("change", (status) => {
          observer.next(status);
        });
        return () => subscription.remove();
      }).pipe(
        filter((status) => Platform.OS !== "web" && status === "active")
      );
    },
  },
});

// Disable per-query by setting the event to false
useQuery(QUERY, { refetchOn: { reactNativeAppStatus: false } });
Manually trigger an event refetch

Refetches can be triggered imperatively by calling emit with the event name and its payload (if any).

refetchEventManager.emit("reactNativeAppStatus", "active");
Sourceless events

A source that has no automatic detection logic but still wants imperative emit support can be declared as true. Type the event as void to omit the payload argument.

declare module "@apollo/client" {
  interface RefetchEvents {
    userTriggered: void;
  }
}

const refetchEventManager = new RefetchEventManager({
  sources: { userTriggered: true },
});

refetchEventManager.emit("userTriggered");

Note: Calling emit on an event without a registered source will log a warning and result in a no-op.

Custom handlers

When an event fires, the default handler calls client.refetchQueries({ include: "active" }) filtered by each query's refetchOn setting. You can override the handler for an event to add your own custom filtering. For example, to refetch all queries, including standby queries, define a handler for the event:

const refetchEventManager = new RefetchEventManager({
  // ...
  handlers: {
    userTriggered: ({ client, source, payload, matchesRefetchOn }) => {
      return client.refetchQueries({
        include: "all",
        onQueryUpdated: (observableQuery) => {
          return matchesRefetchOn(observableQuery);
        },
      });
    },
  },
});

Handlers must return either a RefetchQueriesResult or void. Returning void skips refetching for the event.

  • #​13232 f1b541f Thanks @​jerelmiller! - Version bump to rc.

  • #​13206 08fccab Thanks @​jerelmiller! - Extend the defaultOptions type-safety work to client.mutate and useMutation.

    The errorPolicy option now flows through to the result types for mutations in the same way it already does for queries:

    • ApolloClient.MutateResult<TData, TErrorPolicy> maps errorPolicy to the concrete shape of data and error:
      • "none"{ data: TData; error?: never }
      • "all"{ data: TData | undefined; error?: ErrorLike }
      • "ignore"{ data: TData | undefined; error?: never }
    • client.mutate and useMutation pick up the declared defaultOptions.mutate.errorPolicy and the explicit errorPolicy on each call to narrow return types accordingly.
    • useMutation.Result.error is narrowed to undefined when errorPolicy is "ignore", since client.mutate never resolves with an error in that case.

    DeclareDefaultOptions.Mutate already accepted errorPolicy; the new behavior is that once you declare it, hook and method return types reflect it:

    // apollo.d.ts
    import "@apollo/client";
    
    declare module "@apollo/client" {
      namespace ApolloClient {
        namespace DeclareDefaultOptions {
          interface Mutate {
            errorPolicy: "all";
          }
        }
      }
    }
    const result = await client.mutate({ mutation: MUTATION });
    result.data;
    //     ^? TData | undefined
    result.error;
    //     ^? ErrorLike | undefined

    Setting errorPolicy on an individual call overrides the default for that call's return type.

  • #​13222 b93c172 Thanks @​jerelmiller! - Extend the defaultOptions type-safety work to preloadQuery (returned from createQueryPreloader). Defaults declared in DeclareDefaultOptions.WatchQuery now work with preloadQuery to ensure the PreloadedQueryRef's data states are correctly set.

    // apollo.d.ts
    import "@apollo/client";
    
    declare module "@apollo/client" {
      namespace ApolloClient {
        namespace DeclareDefaultOptions {
          interface WatchQuery {
            errorPolicy: "all";
          }
        }
      }
    }
    const preloadQuery = createQueryPreloader(client);
    const queryRef = preloadQuery(QUERY);
    //    ^? PreloadedQueryRef<TData, TVariables, "complete" | "streaming" | "empty">
  • #​13132 f3ce805 Thanks @​phryneas! - Synchronize method and hook return types with defaultOptions.

    Prior to this change, the following code snippet would always apply:

    declare const MY_QUERY: TypedDocumentNode

Important

✂ PR body was truncated to here.


Configuration

📅 Schedule: (in timezone Asia/Tokyo)

  • Branch creation
    • "on saturday"
  • 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.

👻 Immortal: This PR will be recreated if closed unmerged. Get config help if that's undesired.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

@renovate renovate Bot added the renovate label Jul 16, 2021
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from bc14504 to 6443fee Compare July 20, 2021 18:06
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from a34b011 to 69ecbd8 Compare July 30, 2021 16:48
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 69ecbd8 to 6a1941f Compare August 3, 2021 01:02
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 6a1941f to c0fdb8d Compare August 13, 2021 17:07
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from d3ba2fb to 3a74380 Compare August 27, 2021 17:30
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from 4516411 to 96b29b2 Compare September 10, 2021 16:26
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 96b29b2 to e7d9f71 Compare September 24, 2021 16:34
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from 3fce376 to e670983 Compare October 15, 2021 17:01
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from d3fd266 to a6b4d31 Compare November 5, 2021 17:25
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from a6b4d31 to 719f7f9 Compare November 5, 2021 19:45
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from 33eed47 to e6e26bf Compare December 31, 2021 17:55
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from e6e26bf to b59660f Compare January 18, 2022 23:20
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from b59660f to 09d42f3 Compare February 8, 2022 20:14
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 09d42f3 to 1ef4422 Compare March 26, 2022 15:28
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 1ef4422 to 976260a Compare April 24, 2022 21:30
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 976260a to a1a84e5 Compare May 15, 2022 20:12
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from a1a84e5 to d836216 Compare June 18, 2022 16:50
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from c9d9277 to 530672e Compare September 2, 2025 20:24
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 530672e to c3ffaed Compare September 15, 2025 08:14
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from ffa1d63 to 956ab10 Compare September 30, 2025 22:37
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from 803f4f7 to b7710d8 Compare October 31, 2025 19:37
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from ad59d3c to 874bea6 Compare December 10, 2025 10:59
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 874bea6 to e1a26d0 Compare December 16, 2025 18:13
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from e1a26d0 to 9dea84d Compare December 31, 2025 15:39
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 3 times, most recently from 43570c0 to 7073700 Compare January 16, 2026 02:49
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from b2efcfa to f96c48a Compare January 21, 2026 13:31
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from f96c48a to e8336ed Compare January 28, 2026 21:10
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from 9cbc43f to 45c94af Compare February 12, 2026 17:11
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from 714f9e4 to 283cb63 Compare February 23, 2026 23:43
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 283cb63 to d35c294 Compare April 15, 2026 17:51
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch 2 times, most recently from ee0e8cd to 4ae7397 Compare April 23, 2026 23:00
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 4ae7397 to b2f98ea Compare May 1, 2026 16:17
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from b2f98ea to 64663e7 Compare May 13, 2026 19:58
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 64663e7 to 155cee3 Compare May 22, 2026 00:10
@renovate
renovate Bot force-pushed the renovate/major-apollo-graphql-packages branch from 155cee3 to cc5a0be Compare June 4, 2026 03:36

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants