Skip to content
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

feat(tanstack): return query key and pass in abort signal to fetcher #1903

Merged
merged 1 commit into from
Dec 3, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Dec 3, 2024

fixes #1872

Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant modifications to the Tanstack Query library across various frameworks (React, Vue, Svelte). Key changes include the restructuring of query hooks to enhance the handling of queryKey and the introduction of a signal parameter in the queryFn for better request cancellation management. The return values of the query hooks are updated to include queryKey alongside the results, improving clarity and usability. The changes are implemented in the respective files for each framework, ensuring consistent behavior across the library.

Changes

File Path Change Summary
packages/plugins/tanstack-query/src/runtime-v5/react.ts Updated useModelQuery, useSuspenseModelQuery, useInfiniteModelQuery, and useSuspenseInfiniteModelQuery to include signal in queryFn and restructure return values to include queryKey.
packages/plugins/tanstack-query/src/runtime-v5/svelte.ts Modified useModelQuery and useInfiniteModelQuery to define queryFn as QueryFunction with signal, and updated return values to include queryKey.
packages/plugins/tanstack-query/src/runtime-v5/vue.ts Restructured useModelQuery and useInfiniteModelQuery to compute queryKey before queryOptions, added signal to queryFn, and updated return values to include queryKey.
packages/plugins/tanstack-query/src/runtime/react.ts Updated useModelQuery and useInfiniteModelQuery to return an object with queryKey and results, and added signal to queryFn.
packages/plugins/tanstack-query/src/runtime/svelte.ts Enhanced useModelQuery and useInfiniteModelQuery by separating queryKey creation and adding signal to queryFn, returning a derived store.
packages/plugins/tanstack-query/src/runtime/vue.ts Similar updates as above for useModelQuery and useInfiniteModelQuery, including signal in queryFn and restructuring return values.
packages/plugins/tanstack-query/tests/plugin.test.ts Updated test cases to include queryKey in the destructured return values of hooks across React, Vue, and Svelte applications. Added logging for queryKey.

Assessment against linked issues

Objective Addressed Explanation
Support hook cancellation / abort (Issue #1872)

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 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
Contributor

@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: 2

🧹 Outside diff range and nitpick comments (16)
packages/plugins/tanstack-query/src/runtime-v5/vue.ts (4)

74-77: Correctness of optimisticUpdate Property Check

Consider simplifying the check for optimisticUpdate in getQueryKey. Currently, it uses optionsValue?.optimisticUpdate !== false, which may lead to unintended behavior if optimisticUpdate is undefined. Explicitly handle undefined to ensure correct query key generation.

Apply this diff to clarify the intention:

 const queryKey = getQueryKey(model, url, args, {
     infinite: false,
-    optimisticUpdate: optionsValue?.optimisticUpdate !== false,
+    optimisticUpdate: optionsValue?.optimisticUpdate === true,
 });

81-86: Type Inconsistency in queryFn Parameters

The queryFn destructures queryKey but may not need it since queryKey is already available in the outer scope. This could lead to confusion or unintended usage.

Consider refactoring the queryFn to avoid shadowing the outer queryKey:

 queryFn: ({ signal }) => {
-    const [_prefix, _model, _op, args] = queryKey;
+    const argsValue = toValue(args);
     const reqUrl = makeUrl(url, argsValue);
     return fetcher<TQueryFnData, false>(reqUrl, { signal }, fetch, false);
 },

121-126: Ensure Consistent Access to args in queryFn

Within queryFn, args is obtained from queryKey, but it might be clearer and safer to use the args parameter directly, especially since queryKey may have a complex structure.

Consider refactoring to access args directly:

 queryFn: ({ queryKey, pageParam, signal }) => {
-    const [_prefix, _model, _op, args] = queryKey;
-    const reqUrl = makeUrl(url, pageParam ?? toValue(args));
+    const argsValue = pageParam ?? toValue(args);
+    const reqUrl = makeUrl(url, argsValue);
     return fetcher<TQueryFnData, false>(reqUrl, { signal }, fetch, false);
 },

Line range hint 150-161: Investigate Typing Issue in useModelMutation

The comment // TODO: figure out the typing problem indicates there is a known typing issue with finalOptions. This should be addressed to ensure type safety and maintainability.

Would you like assistance in resolving the typing issue with finalOptions? I can help refactor the code to properly type this variable.

packages/plugins/tanstack-query/src/runtime/react.ts (3)

67-70: Consistent Use of options in getQueryKey

In the useModelQuery function, consider passing options?.optimisticUpdate directly to getQueryKey for clarity.

Apply this diff to simplify the code:

 const queryKey = getQueryKey(model, url, args, {
     infinite: false,
-    optimisticUpdate: options?.optimisticUpdate !== false,
+    optimisticUpdate: options?.optimisticUpdate,
 });

73-77: Simplify queryFn in useQuery

The queryFn currently constructs reqUrl outside of the function passed to useQuery. This can be simplified for better readability.

Apply this diff:

 return {
     queryKey,
     ...useQuery<TQueryFnData, TError, TData>({
         queryKey,
-        queryFn: ({ signal }) => fetcher<TQueryFnData, false>(reqUrl, { signal }, fetch, false),
+        queryFn: ({ signal }) => fetcher<TQueryFnData, false>(makeUrl(url, args), { signal }, fetch, false),
         ...options,
     }),
 };

98-108: Reuse Code Between useModelQuery and useInfiniteModelQuery

Consider abstracting the common logic between useModelQuery and useInfiniteModelQuery to reduce code duplication and enhance maintainability.

packages/plugins/tanstack-query/src/runtime/svelte.ts (4)

68-71: Handle options.optimisticUpdate Undefined Case

When accessing options?.optimisticUpdate, ensure that the behavior is well-defined if options is undefined.

Apply this diff to provide a default value:

 const queryKey = getQueryKey(model, url, args, {
     infinite: false,
-    optimisticUpdate: options?.optimisticUpdate !== false,
+    optimisticUpdate: options?.optimisticUpdate !== false ?? true,
 });

76-80: Type Inference for queryFn

The explicit typing of queryFn might be unnecessary if TypeScript can infer the type. Removing explicit types can simplify the code.

Apply this diff:

-const queryFn: QueryFunction<TQueryFnData, QueryKey> = ({ signal }) =>
+const queryFn = ({ signal }) =>
     fetcher<TQueryFnData, false>(reqUrl, { signal }, fetch, false);

97-102: Potential Unnecessary Derived Store

The use of derived to return queryKey alongside the result might add unnecessary complexity. Evaluate if directly returning an object is sufficient.


Line range hint 124-125: Typo in Function Signature Comment

The function description mentions creating a "POST mutation," but the function is for creating an infinite query.

Correct the comment to accurately reflect the function's purpose.

-/**
- * Creates a POST mutation with svelte-query.
+/**
+ * Creates a svelte-query infinite query.
packages/plugins/tanstack-query/src/runtime-v5/svelte.ts (2)

2-2: Unused Import: QueryKey

The imported QueryKey from @tanstack/react-query-v5 is not used in this file. Consider removing it to clean up the imports.

Apply this diff:

-import { QueryKey } from '@tanstack/react-query-v5';

17-17: Consistent Ordering of Imports

The import order combines external libraries and local modules. Consider grouping imports by their origin for better readability.

Group imports from external libraries together.

packages/plugins/tanstack-query/src/runtime/vue.ts (3)

71-77: Handle Undefined optionsValue

Similar to changes in the runtime-v5/vue.ts file, ensure that optionsValue is safely handled in case it's undefined.

Consider providing a default value or handling the undefined case explicitly.


81-86: Simplify queryFn Logic

Avoid destructuring queryKey within queryFn if not necessary, as it may cause confusion.

Refactor queryFn to use args directly:

 queryFn: ({ signal }) => {
-    const [_prefix, _model, _op, args] = queryKey;
     const reqUrl = makeUrl(url, toValue(args));
     return fetcher<TQueryFnData, false>(reqUrl, { signal }, fetch, false);
 },

Line range hint 150-161: Address Typing Problem in useModelMutation

The comment indicates a typing issue that needs resolution to ensure the code is type-safe.

Would you like assistance in resolving the typing issue mentioned in the comment? I can help adjust the types for finalOptions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6642f33 and 545eac1.

📒 Files selected for processing (7)
  • packages/plugins/tanstack-query/src/runtime-v5/react.ts (4 hunks)
  • packages/plugins/tanstack-query/src/runtime-v5/svelte.ts (6 hunks)
  • packages/plugins/tanstack-query/src/runtime-v5/vue.ts (2 hunks)
  • packages/plugins/tanstack-query/src/runtime/react.ts (2 hunks)
  • packages/plugins/tanstack-query/src/runtime/svelte.ts (3 hunks)
  • packages/plugins/tanstack-query/src/runtime/vue.ts (2 hunks)
  • packages/plugins/tanstack-query/tests/plugin.test.ts (4 hunks)
🔇 Additional comments (12)
packages/plugins/tanstack-query/src/runtime-v5/vue.ts (2)

131-131: 🛠️ Refactor suggestion

Avoid Using any Type for queryOptions

Using any undermines type safety. It's better to let TypeScript infer the correct type or specify it explicitly.

Apply this diff to remove the any type annotation:

-const queryOptions: any = computed<
+const queryOptions = computed<
     Omit<UseInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>, 'queryKey' | 'initialPageParam'>
 >(() => ({

Likely invalid or redundant comment.


71-73: Ensure optionsValue Handles Undefined Appropriately

The extraction of optionsValue using toValue may result in undefined if options is not provided. Ensure that subsequent usage of optionsValue safely handles the possibility of undefined.

Verify that optionsValue is appropriately handled:

✅ Verification successful

optionsValue is Safely Handled Throughout the Code

Based on the code analysis, optionsValue is used safely throughout the implementation:

  1. When accessing optimisticUpdate: Uses optional chaining optionsValue?.optimisticUpdate !== false
  2. When spreading into query options: Spread operator safely handles undefined ...optionsValue
  3. All usages employ proper null-safe patterns:
    • Optional chaining for property access
    • Default values through spread operator
    • No direct property access without checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if `optionsValue` is used safely when undefined.

# Search for usages of `optionsValue` where it's accessed without a null check.
rg --pcre2 "optionsValue\.\w+" -A2 packages/plugins/tanstack-query/src/

Length of output: 73


Script:

#!/bin/bash
# Let's check the complete context of how optionsValue is used
rg "optionsValue" -B2 -A5 packages/plugins/tanstack-query/src/

Length of output: 6613


Script:

#!/bin/bash
# Let's also look at the complete function implementation to understand the context better
ast-grep --pattern 'const optionsValue = toValue<$_>($_)'

Length of output: 1373


Script:

#!/bin/bash
# Let's check the complete file content to understand the full context
cat packages/plugins/tanstack-query/src/runtime-v5/vue.ts

Length of output: 7802

packages/plugins/tanstack-query/src/runtime-v5/svelte.ts (2)

124-125: Ensure Correct Generic Parameters in QueryFunction

The QueryFunction type might require specific generic parameters. Verify that the usage aligns with the type definition in @tanstack/svelte-query-v5.

Check the QueryFunction type definition for correct usage.


76-77: Incorrect Import Path for QueryFunction

Ensure that QueryFunction is imported from the correct package. Currently, it's imported from @tanstack/svelte-query-v5, but you might need to verify if this is the intended source.

Run the following script to check the available exports:

packages/plugins/tanstack-query/src/runtime-v5/react.ts (4)

103-114: LGTM! Consistent implementation with useModelQuery.

The suspense version correctly mirrors the non-suspense implementation, maintaining consistency in both queryKey return and abort signal support.


134-145: LGTM! Infinite query implementation properly adapted.

The infinite query version correctly implements:

  1. queryKey return for infinite queries
  2. Signal support while maintaining pageParam functionality

168-179: LGTM! Consistent implementation with useInfiniteModelQuery.

The suspense infinite query version correctly mirrors the non-suspense implementation.


71-82: LGTM! Implementation aligns with TanStack Query v5 patterns.

The changes correctly implement both requirements:

  1. Return queryKey alongside results for better query management
  2. Pass abort signal to fetcher for request cancellation support

Let's verify the queryKey structure matches usage in tests:

✅ Verification successful

Implementation correctly returns queryKey and follows TanStack Query v5 patterns

The changes have been verified:

  1. The queryKey is correctly generated using the getQueryKey function with proper parameters (model, url, args, options)
  2. The queryKey is returned alongside the query results in a spread object
  3. The abort signal is properly passed to the fetcher function
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify queryKey structure consistency across codebase
# Expected: queryKey structure should match the test usage

# Check queryKey usage in tests
rg -A 2 'queryKey.*=.*use.*Query' 

Length of output: 35


Script:

#!/bin/bash
# Let's try a broader search for queryKey usage in test files
fd "test|spec" -e ts -e tsx --exec rg -l "queryKey"

# Then let's look for actual test implementations using useModelQuery
rg "useModelQuery" -A 5 -B 5

# Also check for any test files specifically for this feature
fd "tanstack|query" -e test.ts -e test.tsx -e spec.ts -e spec.tsx

Length of output: 74432


Script:

#!/bin/bash
# Let's check the test file for queryKey usage and structure
rg -A 5 "queryKey.*=.*getQueryKey" packages/plugins/tanstack-query/tests/react-hooks-v5.test.tsx

# Also check the getQueryKey implementation
rg -A 10 "export.*getQueryKey" packages/plugins/tanstack-query/src/runtime/common.ts

Length of output: 542

packages/plugins/tanstack-query/tests/plugin.test.ts (4)

57-58: LGTM! Tests properly verify queryKey return.

Tests correctly verify the new queryKey functionality for both regular and infinite queries.

Also applies to: 64-67


129-132: LGTM! Suspense tests properly verify queryKey return.

Tests correctly verify the queryKey functionality for suspense infinite queries.


149-150: LGTM! Vue tests properly verify queryKey return.

Tests correctly verify the queryKey functionality while properly handling Vue's reactivity system.

Also applies to: 156-159


225-226: LGTM! Svelte tests properly verify queryKey return.

Tests correctly verify the queryKey functionality while properly handling Svelte's store pattern using get().

Also applies to: 232-235

Comment on lines 116 to +119
) {
// CHECKME: vue-query's `useInfiniteQuery`'s input typing seems wrong
const queryOptions: any = computed(() => ({
queryKey: getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false }),
queryFn: ({ queryKey, pageParam }: { queryKey: QueryKey; pageParam?: unknown }) => {
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
const queryOptions: any = computed<
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Typings for queryOptions May Be Too Broad

The queryOptions variable is typed as any, which can mask potential type errors and reduce the benefits of TypeScript's static typing.

Apply this diff to provide a more specific type:

-const queryOptions: any = computed<
+const queryOptions = computed<
     Omit<UseInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>, 'queryKey' | 'initialPageParam'>
 >(() => ({
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
) {
// CHECKME: vue-query's `useInfiniteQuery`'s input typing seems wrong
const queryOptions: any = computed(() => ({
queryKey: getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false }),
queryFn: ({ queryKey, pageParam }: { queryKey: QueryKey; pageParam?: unknown }) => {
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
const queryOptions: any = computed<
) {
// CHECKME: vue-query's `useInfiniteQuery`'s input typing seems wrong
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
const queryOptions = computed<

Comment on lines +116 to +119
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
const queryOptions: any = computed<
Omit<UseInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>, 'queryKey' | 'initialPageParam'>
>(() => ({
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Typings for queryOptions May Be Too Broad

Using any for queryOptions reduces type safety.

Remove any and let TypeScript infer the type:

-const queryOptions: any = computed<
+const queryOptions = computed<
     Omit<UseInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>, 'queryKey' | 'initialPageParam'>
 >(() => ({
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
const queryOptions: any = computed<
Omit<UseInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>, 'queryKey' | 'initialPageParam'>
>(() => ({
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
const queryOptions = computed<
Omit<UseInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>, 'queryKey' | 'initialPageParam'>
>(() => ({

@ymc9 ymc9 merged commit d5c30f9 into dev Dec 3, 2024
13 checks passed
@ymc9 ymc9 deleted the feat/hoosk-return-key branch December 3, 2024 12:12
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