Skip to content

feat(react-query): add mutationOptions #4

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 16, 2025

mutationOptions helps extracting mutation options into separate functions.

Summary by CodeRabbit

  • New Features

    • Introduced a new helper function for mutation options, enabling stronger type safety and flexible option handling for mutation hooks.
  • Documentation

    • Added comprehensive documentation for the new mutation options helper, including usage examples and TypeScript guidance.
  • Tests

    • Implemented new test suites to ensure correct type inference and behavior of the mutation options helper.

@arvi18
Copy link
Author

arvi18 commented Apr 16, 2025

View your CI Pipeline Execution ↗ for commit ff15e5d.

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

☁️ Nx Cloud last updated this comment at 2025-04-07 08:18:32 UTC

@arvi18
Copy link
Author

arvi18 commented Apr 16, 2025

More templates

@tanstack/angular-query-devtools-experimental

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

@tanstack/angular-query-experimental

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

@tanstack/eslint-plugin-query

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

@tanstack/query-async-storage-persister

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

@tanstack/query-broadcast-client-experimental

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

@tanstack/query-core

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

@tanstack/query-devtools

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

@tanstack/query-persist-client-core

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

@tanstack/query-sync-storage-persister

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

@tanstack/react-query

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

@tanstack/react-query-devtools

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

@tanstack/react-query-next-experimental

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

@tanstack/react-query-persist-client

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

@tanstack/solid-query

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

@tanstack/solid-query-devtools

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

@tanstack/solid-query-persist-client

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

@tanstack/svelte-query

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

@tanstack/svelte-query-devtools

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

@tanstack/svelte-query-persist-client

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

@tanstack/vue-query

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

@tanstack/vue-query-devtools

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

commit: ff15e5d

@gandalf-repo
Copy link

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 16, 2025

✅ Actions performed

Full review triggered.

Copy link

coderabbitai bot commented Apr 16, 2025

Walkthrough

This update introduces comprehensive support for a new mutationOptions utility in a React Query-like library. The changes include the implementation of the mutationOptions function with strong TypeScript typings, extensive documentation describing its usage and function signature, and new test suites to verify both runtime and type-level behaviors. The documentation and examples clarify how to extract and reuse mutation options in a type-safe manner, and the tests ensure correct type inference and error detection. No existing exported or public APIs are modified; all changes are additive.

Changes

File(s) Change Summary
docs/framework/react/reference/mutationOptions.md Added new documentation describing the mutationOptions function signature and its supported options.
docs/framework/react/typescript.md Added a section on "Typing Mutation Options" with examples using the new mutationOptions helper for reusable and type-safe mutation options.
packages/react-query/src/mutationOptions.ts Introduced the mutationOptions function with multiple TypeScript overloads and supporting types for flexible and precise mutation option handling.
packages/react-query/src/tests/mutationOptions.test-d.tsx Added a new TypeScript test suite verifying type inference, error detection, and tagging behavior of the mutationOptions function.
packages/react-query/src/tests/mutationOptions.test.tsx Added a runtime test to ensure that mutationOptions returns the input object unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CustomHook
    participant mutationOptions
    participant useMutation

    User->>CustomHook: Call custom hook (e.g., useGroupPostMutation)
    CustomHook->>mutationOptions: Prepare mutation options object
    mutationOptions-->>CustomHook: Return options (typed and tagged)
    CustomHook->>useMutation: Pass options to useMutation
    useMutation-->>CustomHook: Return mutation result
    CustomHook-->>User: Provide mutation utilities
Loading

Poem

🐇
A hop and a skip, mutation options appear,
With typings so strong, there’s nothing to fear!
Docs and tests join in, all neat and precise,
Type errors are banished — oh, isn’t that nice?
Now rabbits can code, mutate, and reuse,
With helpers and hooks, there’s no way to lose!
🌱✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
docs/framework/react/reference/mutationOptions.md (1)

13-15: Consider using a proper markdown heading instead of emphasis.

Use a markdown heading (e.g., ## Options) instead of bold text (**Options**) for better document structure and consistency with other documentation files.

-**Options**
+## Options
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

13-13: Emphasis used instead of a heading
null

(MD036, no-emphasis-as-heading)

packages/react-query/src/__tests__/mutationOptions.test-d.tsx (2)

6-13: Suppress ESLint warning about missing assertions

This test case correctly validates that the TypeScript compiler rejects excess properties, but there's an ESLint warning about the test having no assertions (vitest/expect-expect). While the test is valid (using @ts-expect-error as a compile-time assertion), you should suppress the warning.

  it('should not allow excess properties', () => {
+    // eslint-disable-next-line vitest/expect-expect
    return mutationOptions({
      mutationFn: () => Promise.resolve(5),
      mutationKey: ['key'],
      // @ts-expect-error this is a good error, because onMutates does not exist!
      onMutates: 1000,
    })
  })
🧰 Tools
🪛 GitHub Actions: pr

[warning] 6-6: ESLint warning: Test has no assertions (vitest/expect-expect).


1-51: Consider adding more comprehensive type tests

While the current tests cover basic type inference scenarios, consider adding tests for:

  1. Variable argument types in mutationFn (e.g., testing that a mutation function's parameter types are correctly inferred)
  2. Complex nested types in the mutation result
  3. Type behavior with generics
  4. Error type inference (if applicable)

These would strengthen the type-checking coverage and ensure robust type safety for users.

🧰 Tools
🪛 GitHub Actions: pr

[warning] 6-6: ESLint warning: Test has no assertions (vitest/expect-expect).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a5990e and ff15e5d.

📒 Files selected for processing (5)
  • docs/framework/react/reference/mutationOptions.md (1 hunks)
  • docs/framework/react/typescript.md (1 hunks)
  • packages/react-query/src/__tests__/mutationOptions.test-d.tsx (1 hunks)
  • packages/react-query/src/__tests__/mutationOptions.test.tsx (1 hunks)
  • packages/react-query/src/mutationOptions.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/react-query/src/__tests__/mutationOptions.test-d.tsx (1)
packages/react-query/src/mutationOptions.ts (1)
  • mutationOptions (103-105)
packages/react-query/src/__tests__/mutationOptions.test.tsx (1)
packages/react-query/src/mutationOptions.ts (1)
  • mutationOptions (103-105)
packages/react-query/src/mutationOptions.ts (2)
packages/query-core/src/types.ts (5)
  • DefaultError (40-44)
  • InitialDataFunction (156-156)
  • OmitKeyof (12-22)
  • MutationFunction (1095-1097)
  • DataTag (66-75)
packages/angular-query-experimental/src/types.ts (1)
  • NonUndefinedGuard (315-315)
🪛 markdownlint-cli2 (0.17.2)
docs/framework/react/reference/mutationOptions.md

13-13: Emphasis used instead of a heading
null

(MD036, no-emphasis-as-heading)

🪛 GitHub Actions: pr
packages/react-query/src/__tests__/mutationOptions.test-d.tsx

[warning] 6-6: ESLint warning: Test has no assertions (vitest/expect-expect).

🔇 Additional comments (16)
packages/react-query/src/mutationOptions.ts (7)

1-10: Imports look good and match the functionality.

The imports include all necessary types from the query-core package and internal types needed for the implementation.


11-21: Well-structured type definition for UndefinedInitialDataOptions.

The type correctly extends UseMutationOptions and properly defines initialData as optional, allowing either undefined values or a function returning non-undefined data.


23-41: Properly defined UnusedSkipTokenOptions type.

This type correctly omits the mutationFn from UseMutationOptions and redefines it as optional, excluding SkipToken and undefined. The use of OmitKeyof is appropriate here for precise type control.


43-43: NonUndefinedGuard utility type is properly implemented.

This utility type correctly excludes undefined from a generic type T, which is essential for enforcing the presence of values in the typed options.


45-58: DefinedInitialDataOptions type ensures initialData is defined.

The type properly ensures that initialData is always defined (non-undefined) either directly or through a function, while making mutationFn optional.


60-74: Function overloads provide proper type inference.

The three overloads for mutationOptions correctly handle different option types and augment them with a typed mutationKey. This enables TypeScript to correctly infer types based on the options provided.

Also applies to: 76-85, 87-101


103-105: Implementation is minimal and correct.

The function simply returns the input options without modification, serving as a type utility rather than a runtime transformer. This matches the pattern used in queryOptions and is sufficient for providing type inference benefits.

packages/react-query/src/__tests__/mutationOptions.test.tsx (2)

1-4: Test imports are appropriate.

The necessary testing utilities and the function to be tested are properly imported.


5-14: Test correctly verifies the function's runtime behavior.

The test effectively confirms that mutationOptions returns the exact same object that was passed to it without any modifications, which is the expected behavior for this type utility function.

docs/framework/react/reference/mutationOptions.md (1)

1-12: Documentation frontmatter and code example look good.

The documentation properly defines the ID and title, and shows a clear code example of the mutationOptions function signature.

docs/framework/react/typescript.md (1)

242-259: Great addition of Typing Mutation Options section.

This new section effectively explains how to use mutationOptions to extract mutation options into a separate function, similar to the existing queryOptions. The example is clear and demonstrates a practical use case including handling the mutationKey, mutationFn, and callbacks.

packages/react-query/src/__tests__/mutationOptions.test-d.tsx (5)

1-4: LGTM!

The imports look good. The file correctly imports testing utilities from vitest, the dataTagSymbol from the core package, and the mutationOptions function being tested.


15-23: LGTM! Well-implemented type inference test

This test successfully verifies that the TypeScript compiler correctly infers the type of the data parameter in the onSuccess callback based on the return type of mutationFn. This ensures type safety when working with mutation results.


25-32: LGTM! Excellent type tagging test

The test correctly verifies that the mutationKey is tagged with the result type of the mutation function. This is crucial for maintaining type safety throughout the query system.


34-40: LGTM! Good fallback type test

This test correctly verifies the fallback behavior when no mutationFn is provided - the mutationKey should be tagged with unknown since there's no way to infer the data type.


42-51: LGTM! Properly testing type preservation with callbacks

This test ensures that adding an onSuccess callback doesn't affect the type tagging of the mutationKey. This is important for consistent type inference throughout the library.

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.

3 participants