Skip to content

Issue #8469 - fix(solid-query): client() doesn't return undefined #3

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 4 commits into
base: main
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 16, 2025

Issue TanStack#8469 - fix(solid-query): client() doesn't return undefined

Summary by CodeRabbit

  • Tests

    • Added a new test to verify correct handling of dependent queries within routed environments, ensuring no errors and proper data rendering.
  • Chores

    • Added the @solidjs/router package as a development dependency.
  • Refactor

    • Updated internal memoization logic to enhance the initialization behavior of query clients.

@arvi18
Copy link
Author

arvi18 commented Apr 16, 2025

Thank you very much for taking a look into this @gopnik5!

I cannot make a statement about the implementation of the fix, but a test I wrote locally for the issue indeed passes now. Maybe it is useful to you as template for a regression test (in useQuery.test.tsx)

// ...
// I only managed to reproduce the issue with @solidjs/router, so I had to add it to devDependencies
import { Route, MemoryRouter, createMemoryHistory } from '@solidjs/router'

describe('useQuery', () => {
  // ...

  it('should not reproduce issue #8469', async () => {
    const queryCache = new QueryCache()
    const queryClient = new QueryClient({ queryCache });

    const history = createMemoryHistory();

    const errorHandler = vi
      .fn<(err: unknown) => void>()

    function App() {

      return (
        <ErrorBoundary
          fallback={(err) => {
            errorHandler(err)
            return err.message
          }}
        >
          <Suspense>
            <MemoryRouter history={history}>
              <Route path="/" component={Index} />
              <Route path="/sub" component={Sub} />
            </MemoryRouter>
          </Suspense>
        </ErrorBoundary>
      )
    }

    queryClient.setQueryData(['parent'], { id: 123})

    function Index() {
      return 'Index'
    }

    function Sub() {
      const parent = useQuery(() => ({
        queryKey: ['parent'],
        async queryFn() {
          await new Promise((r) => setTimeout(r, 100))
          return {
            id: 123,
          }
        },
        // refetchOnMount: false, // this would remove the error
      }))

      const childQuery = useQuery(() => ({
        queryKey: ['sub', parent.data?.id],
        // enabled: parent.data?.id != null,
        async queryFn() {
          await new Promise((r) => setTimeout(r, 200))
          return Promise.resolve('child' + parent.data?.id)
        },
      }))
      return <pre>{childQuery.data}</pre>
    }

    const rendered = render(() => (
      <QueryClientProvider client={queryClient}>
        <App />
      </QueryClientProvider>
    ))

    await waitFor(() => rendered.getByText('Index'))

    // Navigate to the sub page to trigger the error
    history.set({
      value: '/sub',
    })

    // Wait for the error to occur
    await sleep(200)

    expect(errorHandler).not.toHaveBeenCalled()

    await waitFor(() => {
      expect(rendered.getByText('child123')).toBeInTheDocument()
    })
  })
})

@arvi18
Copy link
Author

arvi18 commented Apr 16, 2025

Thank you! I'll take a look.

@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

The changes introduce a new development dependency, @solidjs/router, to the @tanstack/solid-query package. A new test case is added to verify correct handling of dependent queries within a Solid.js routing context, ensuring queries are managed properly across route transitions. Additionally, the memoization logic for the query client within the useBaseQuery function is updated to provide an initial value, potentially affecting update behavior. No public API or exported entity signatures are altered.

Changes

File(s) Change Summary
packages/solid-query/package.json Added @solidjs/router@^0.15.3 to devDependencies.
packages/solid-query/src/tests/useQuery.test.tsx Added a test for dependent queries in a routed environment using Solid.js router and new imports for routing.
packages/solid-query/src/useBaseQuery.ts Updated createMemo usage to include an initial value for the memoized query client.

Poem

In the warren of code, a new path appears,
With routers and queries, we hop without fears.
Memoized memories, dependencies align,
Testing new journeys, all working just fine.
🐇✨

With every new route, our queries stay bright—
Solid and steady, from morning to night!

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: 1

📜 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 49addbc.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • packages/solid-query/package.json (1 hunks)
  • packages/solid-query/src/__tests__/useQuery.test.tsx (3 hunks)
  • packages/solid-query/src/useBaseQuery.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/solid-query/src/useBaseQuery.ts (2)
packages/solid-query/src/index.ts (1)
  • useQueryClient (99-99)
packages/solid-query/src/QueryClientProvider.tsx (1)
  • useQueryClient (14-25)
🪛 GitHub Actions: pr
packages/solid-query/package.json

[error] 1-1: pnpm install failed with frozen-lockfile because pnpm-lock.yaml is outdated and does not match devDependencies in package.json. Update the lockfile or run 'pnpm install --no-frozen-lockfile'.

🪛 GitHub Actions: autofix.ci
packages/solid-query/package.json

[error] 1-1: pnpm install failed with exit code 1 due to outdated lockfile. The 'pnpm-lock.yaml' devDependencies do not match those in package.json. Run 'pnpm install' without --frozen-lockfile to update the lockfile.

🔇 Additional comments (3)
packages/solid-query/package.json (1)

72-72:

❓ Verification inconclusive

New dependency added to support routing tests.

The @solidjs/router dependency has been added to support the new test case that verifies proper handling of dependent queries in a routing context.

The pipeline is failing because the lockfile hasn't been updated. Please run:


🏁 Script executed:

#!/bin/bash
# Check for missing lockfile update
if grep -q "pnpm install failed with frozen-lockfile" <<< "$PIPELINE_FAILURES"; then
  echo "Please run 'pnpm install' to update the lockfile after adding @solidjs/router"
fi

Length of output: 52


Action Required: Verify Lockfile Update

The new dependency (@solidjs/router) has been added to support the routing tests. However, while the original note indicates that the pipeline is failing due to an outdated lockfile, our automated check did not capture any error message (e.g., "pnpm install failed with frozen-lockfile"). This discrepancy suggests that the pipeline failure might not be strictly due to the lockfile being out-of-date, or the error message isn’t matching the expected output.

  • Location: packages/solid-query/package.json at line 72, where "@solidjs/router": "^0.15.3" is defined.
  • Recommendation: Please manually verify that the lockfile (typically pnpm-lock.yaml) has been updated to reflect the new dependency. If it hasn’t, run pnpm install to update it.
packages/solid-query/src/__tests__/useQuery.test.tsx (2)

5-5: Added imports for Suspense and router-related components.

These new imports are necessary for the new dependent queries test case that tests behavior in a routing context.

Also applies to: 15-15


6051-6124: Added regression test for Issue TanStack#8469.

This test verifies that dependent queries (where one query depends on data from another) work correctly in a routing context. It ensures that the query client is properly initialized and accessible when navigating between routes.

The test creates a routing setup with parent and child queries, where the child query depends on data from the parent query. This effectively tests the fix in useBaseQuery.ts where the client memo now receives an initial value.

Comment on lines +119 to +122
const client = createMemo(
() => useQueryClient(queryClient?.()),
useQueryClient(queryClient?.()),
)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fixed client initialization by providing initial value to createMemo.

This change ensures that the query client is properly initialized with an initial value, resolving the issue where client() doesn't return undefined as expected.

The second parameter to createMemo provides an immediate value that will be used before the first execution of the memo function, ensuring the client is available immediately.

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