Skip to content

Allow implicit passing of fragment arguments via from argument - #13522

Merged
jerelmiller merged 141 commits into
release-4.4from
jerel/fragment-arg-vars
Nov 13, 2026
Merged

jerelmiller merged 141 commits into
release-4.4from
jerel/fragment-arg-vars

Conversation

@jerelmiller

@jerelmiller jerelmiller commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

When reading fragments with useFragment or other fragment APIs, variables in fragments needed the variables option in order to read the right values. When using fragment colocation with queries where the queries, this means ensuring the operation variables are passed down to the component to ensure the fragment is read correctly.

With the introduction of fragment variables in #13508, this problem is further highlighted when fragment arguments contain literal values.

This PR embeds the fragment and operation variables in the parent object so that variables no longer needs to be provided to fragment APIs when the parent object is used as the from value.

const fragment = gql`
  fragment UserCard($avatarSize: Int) on User {
    id
    name
    avatar(size: $avatarSize)
  }
`
const query = gql`
  query GetUserCards {
    currentUser {
      ...UserCard(avatarSize: 96)
    }
    users {
      ...UserCard(avatarSize: $avatarSize)
    }
  }
`;

const { data } = useQuery(query, { variables: { avatarSize: 32 });

// contains the avatar with size: 96
const { data } = useFragment({ fragment, from: data.currentUser })

// contains the list of users with that have avatar with size: $avatarSize
const { data } = useFragment({ fragment, from: data.users })

@apollo-librarian

apollo-librarian Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ Docs preview has no changes

The preview was not built because there were no changes.

Build ID: 27719bab081138832b3f4e20
Build Logs: View logs


✅ AI Style Review — No Changes Detected

No MDX files were changed in this pull request.

Review Log: View detailed log

This review is AI-generated. Please use common sense when accepting these suggestions, as they may not always be accurate or appropriate for your specific context.

@changeset-bot

changeset-bot Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 08bd301

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@apollo/client Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0d33827f-6e0e-4189-89b6-f6ed07fb3792

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Walkthrough

This change adds fragment-variable scope resolution and metadata propagation across cache, client, utility, and React fragment APIs. Cache reads and writes accept root fragment variables, while result objects retain operation and fragment variables for subsequent fragment operations.

Changes: Fragment Variable Support

Layer / File(s) Summary
Fragment scopes and document utilities
src/utilities/internal/*, src/utilities/internal/types/*, src/utilities/internal/__tests__/*, .api-reports/api-report-utilities_internal.api.md
Fragment traversal derives variable scopes. Generated fragment-query documents declare selected-fragment variables and mark the root spread. Masked-spread transformation supports remove and mark modes.
Cache scope evaluation and fragment metadata
src/cache/core/cache.ts, src/cache/inmemory/*, src/cache/inmemory/__tests__/*, .api-reports/api-report-cache.api.md, .api-reports/api-report.api.md
Cache APIs accept root fragment variables. Cache reads, writes, diffs, and watches evaluate fragment scopes and record fragment metadata. Fragment watch identity includes root variables, and array watches are memoized by their observables.
Client result propagation and masking
src/core/ApolloClient.ts, src/local-state/LocalState.ts, src/masking/maskDefinition.ts, src/core/__tests__/*, src/__tests__/*, src/react/query-preloader/__tests__/*, src/testing/internal/*, .api-reports/api-report-core.api.md
Client document transforms select mark mode for caches that support fragment variables. Local-state execution uses fragment scopes, and masking preserves metadata on results. Tests assert metadata across query, read, write, watch, streaming, and data-masking paths.
React fragment observables
src/react/hooks/*, src/react/internal/cache/*, src/react/hooks/__tests__/*, .api-reports/api-report-react_internal.api.md
Fragment hooks pass options to watchFragment. Suspense fragment references receive observables directly and are looked up by observable identity.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant MaskedQueryResult
  participant ApolloCacheWatchFragment
  participant InMemoryCache
  MaskedQueryResult->>ApolloCacheWatchFragment: fragment metadata and source
  ApolloCacheWatchFragment->>InMemoryCache: watch with root fragment variables
  InMemoryCache->>ApolloCacheWatchFragment: fragment data and result metadata
Loading

Possibly related PRs

Suggested reviewers: phryneas

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Allow implicit passing of fragment arguments via from argument" matches the main change. The summary shows fragment variables now flow implicitly through the from option across cache re…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description states the problem: fragment reads through useFragment and other fragment APIs need the operation's variables option to read correct values, especially with literal fragment argument…
Full details: Title check

Explanation

The title "Allow implicit passing of fragment arguments via from argument" matches the main change. The summary shows fragment variables now flow implicitly through the from option across cache reads, writes, watches, diffs, fragment observables, and React fragment hooks, with supporting tests and API report updates. The title is specific and does not describe unrelated work.

Full details: Description check

Explanation

The description states the problem: fragment reads through useFragment and other fragment APIs need the operation's variables option to read correct values, especially with literal fragment arguments. It also states the fix: fragment and operation variables are embedded in the parent object so the from value carries them, and the variables option is no longer required. The changeset matches this description, which covers the cache, fragment observables, read and write paths, and the fragment hooks. The description includes a usage example that matches the changes to fragment argument handling.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Review coverage is incomplete: 1 file could not be fully reviewed. Findings from completed review steps are included; see review info for details.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the fragment scope,
Then carries variables in its tote.
The cache returns the fields in view,
With spread-bound values tagged there too.
The hooks watch each result glow,
And hop where scoped variables go.

@pkg-pr-new

pkg-pr-new Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
npm i https://pkg.pr.new/@apollo/client@13522

commit: 08bd301

@jerelmiller
jerelmiller merged commit 6f94cfb into release-4.4 Nov 13, 2026
52 checks passed
jerelmiller pushed a commit that referenced this pull request Nov 13, 2026
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to release-4.4, this
PR will be updated.

⚠️⚠️⚠️⚠️⚠️⚠️

`release-4.4` is currently in **pre mode** so this branch has
prereleases rather than normal releases. If you want to exit
prereleases, run `changeset pre exit` on `release-4.4`.

⚠️⚠️⚠️⚠️⚠️⚠️

# Releases
## @apollo/client@4.4.0-alpha.1

### Minor Changes

- [#13522](#13522)
[`6f94cfb`](6f94cfb)
Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fragment APIs
now read fragment arguments and operation variables from the object
passed to `from`. When you pass an object from a query result, you no
longer need to pass `variables` to read the fragment with the correct
values.

    ```ts
    const fragment = gql`
      fragment UserCard($avatarSize: Int) on User {
        id
        avatar(size: $avatarSize)
      }
    `;

    const query = gql`
      query GetUsers($friendAvatarSize: Int) {
        currentUser {
          ...UserCard(avatarSize: 96)
          friends {
            ...UserCard(avatarSize: $friendAvatarSize)
          }
        }
      }
    `;

const { data } = useQuery(query, { variables: { friendAvatarSize: 32 }
});

    // Reads the avatar with `size: 96`
    useFragment({ fragment, from: data.currentUser });

    // Reads the avatars with `size: 32`
    useFragment({ fragment, from: data.currentUser.friends });
    ```

This works with `useFragment`, `useSuspenseFragment`, `watchFragment`,
`readFragment`, `writeFragment`, and `updateFragment`. The same applies
to fragments that use operation variables without fragment arguments.

- [#13521](#13521)
[`7bd29db`](7bd29db)
Thanks [@phryneas](https://github.com/phryneas)! -
`CombinedGraphQLErrors` and `CombinedProtocolErrors` now extend
`AggregateError`.
This means that you will need to use at least `lib: ["es2021"]` or `lib:
["es2021.promise"]` in your TypeScript configuration.

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant