Skip to content

refactor: simplify setQueryData by using ensure directly instead of get then ensure #9217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

braden-w
Copy link
Contributor

This commit builds on the changes from #9216.

Refactored the setQueryData method in QueryClient to simplify its logic and improve readability.

The previous implementation of setQueryData was redundant:

  1. It first called this.#queryCache.get() to retrieve an existing query.
  2. Then, it called this.#queryCache.ensure() which internally also performs a "get or create" operation.

This meant the query was potentially being retrieved or checked for existence twice. The ensure() method already handles the logic of getting an existing query or creating a new one if it doesn't exist.

The setQueryData method has been updated to:

  1. Directly call this.#queryCache.ensure() to get or create the query.
  2. Use the returned query instance to access state.data for the functionalUpdate.
  3. Call setData() on the same query instance.

Before:

    const query = this.#queryCache.get<TInferredQueryFnData>(
      defaultedOptions.queryHash,
    )
    const prevData = query?.state.data
    const data = functionalUpdate(updater, prevData)

    if (data === undefined) {
      return undefined
    }

    return this.#queryCache
      .ensure(this, defaultedOptions)
      .setData(data, { ...options, manual: true })

After:

    const query = this.#queryCache.ensure<TInferredQueryFnData>(
      this,
      defaultedOptions,
    )
    const prevData = query.state.data
    const data = functionalUpdate(updater, prevData)

    if (data === undefined) {
      return undefined
    }

    return query.setData(data, { ...options, manual: true })

braden-w added 2 commits May 29, 2025 10:30
Renamed cache methods in QueryCache and MutationCache to better reflect their behavior and improve developer understanding:

- `QueryCache.build()` → `QueryCache.ensure()`
- `MutationCache.build()` → `MutationCache.create()`
- Enhanced documentation for `QueryCache.get()` to clarify retrieval-only behavior

The previous naming was confusing because both `QueryCache.build()` and `MutationCache.build()` had the same name but fundamentally different behaviors:

- **QueryCache.build()**: Used a "get or create" pattern - retrieved existing queries or created new ones
- **MutationCache.build()**: Always created new mutation instances (since each mutation execution should be unique)

This inconsistency made the API harder to understand and could lead to incorrect assumptions about behavior.

## Changes

### QueryCache
- **`build()` → `ensure()`**: Better conveys "ensure this query exists" semantics
- **Enhanced `get()` documentation**: Clarifies it only retrieves existing queries, returns `undefined` if not found
- **Improved `ensure()` documentation**: Explains the "get or create" behavior and when to use it

### MutationCache
- **`build()` → `create()`**: Clearly indicates it always creates new mutation instances
- **Enhanced documentation**: Explains why mutations are always created new (each execution should be unique)

### Updated References
Updated all usages across the codebase:
- `packages/query-core/src/queryClient.ts` - Updated QueryCache method calls
- `packages/query-core/src/queryObserver.ts` - Updated QueryCache method calls
- `packages/query-core/src/mutationObserver.ts` - Updated MutationCache method calls
- `packages/query-core/src/hydration.ts` - Updated both cache method calls
- `packages/query-core/src/__tests__/utils.ts` - Updated test utilities
- `packages/query-persist-client-core/src/__tests__/persist.test.ts` - Updated test
- `packages/query-broadcast-client-experimental/src/index.ts` - Updated broadcast client
…of `get` then `ensure`

This commit builds on the changes from TanStack#9216.

Refactored the `setQueryData` method in `QueryClient` to simplify its logic and improve readability.

The previous implementation of `setQueryData` was redundant:

1. It first called `this.#queryCache.get()` to retrieve an existing query.
2. Then, it called `this.#queryCache.ensure()` which internally also performs a "get or create" operation.

This meant the query was potentially being retrieved or checked for existence twice. The `ensure()` method already handles the logic of getting an existing query or creating a new one if it doesn't exist.

The `setQueryData` method has been updated to:

1. Directly call `this.#queryCache.ensure()` to get or create the query.
2. Use the returned query instance to access `state.data` for the `functionalUpdate`.
3. Call `setData()` on the same query instance.

**Before:**

```typescript
    const query = this.#queryCache.get<TInferredQueryFnData>(
      defaultedOptions.queryHash,
    )
    const prevData = query?.state.data
    const data = functionalUpdate(updater, prevData)

    if (data === undefined) {
      return undefined
    }

    return this.#queryCache
      .ensure(this, defaultedOptions)
      .setData(data, { ...options, manual: true })
```

**After:**

```typescript
    const query = this.#queryCache.ensure<TInferredQueryFnData>(
      this,
      defaultedOptions,
    )
    const prevData = query.state.data
    const data = functionalUpdate(updater, prevData)

    if (data === undefined) {
      return undefined
    }

    return query.setData(data, { ...options, manual: true })
```
Copy link

nx-cloud bot commented May 29, 2025

View your CI Pipeline Execution ↗ for commit 169eba0.

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ❌ Failed 4m 35s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 47s View ↗

☁️ Nx Cloud last updated this comment at 2025-05-29 17:53:08 UTC

Copy link

pkg-pr-new bot commented May 29, 2025

More templates

@tanstack/angular-query-devtools-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@9217

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9217

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9217

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9217

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9217

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@9217

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@9217

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9217

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9217

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@9217

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@9217

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9217

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9217

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@9217

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9217

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9217

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@9217

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9217

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9217

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@9217

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9217

commit: 169eba0

@braden-w
Copy link
Contributor Author

Please disregard the pull request; I realized that this logic incorrectly creates a new query even if the query was not found. The original implementation was correct!

@braden-w braden-w closed this May 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant