-
Notifications
You must be signed in to change notification settings - Fork 406
fix(shared): Avoid revalidating first page on infinite pagination #7153
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
🦋 Changeset detectedLatest commit: eb129f4 The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
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 |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughTests switched from sequential mockReturnValueOnce to deferred-promise-based mocks; MockClerkProvider now memoizes an SWR config via React state to keep the provider stable; usePagesOrInfinite adds cachingSWRInfiniteOptions and uses it with useSWRInfinite. A changeset was added. Changes
Sequence Diagram(s)sequenceDiagram
participant Test as Test
participant Fixture as MockClerkProvider
participant Hook as usePagesOrInfinite / useSWRInfinite
Note over Test,Fixture: createDeferredPromise & memoized swrConfig via state
Test->>Fixture: render provider (stable swrConfig)
Test->>Hook: mount hook -> initial page fetch
Hook->>Test: returns page 1 data
Test->>Hook: call fetchNext()
Note right of Test: resolve deferred promise with page 2
Hook->>Test: returns merged pages (page1 + page2)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this 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
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsx (1)
69-70: VerifymockRejectedValue(null)usage.Rejecting promises with
nullis unconventional. Promise rejections typically use Error instances. Consider:
- If these methods shouldn't be called in this test, use
mockReturnValue()with an empty result instead- If testing error handling, reject with a proper Error:
mockRejectedValue(new Error('...'))- If
nullrejection is intentional for testing specific error handling, add a comment explaining why
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
packages/clerk-js/src/test/create-fixtures.tsx(3 hunks)packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx(5 hunks)packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsx(9 hunks)packages/shared/src/react/hooks/usePagesOrInfinite.ts(4 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/shared/src/react/hooks/usePagesOrInfinite.tspackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/shared/src/react/hooks/usePagesOrInfinite.tspackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/shared/src/react/hooks/usePagesOrInfinite.tspackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/shared/src/react/hooks/usePagesOrInfinite.tspackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/shared/src/react/hooks/usePagesOrInfinite.tspackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/shared/src/react/hooks/usePagesOrInfinite.tspackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsxpackages/clerk-js/src/test/create-fixtures.tsx
**/*.test.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsxpackages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsx (2)
packages/shared/src/utils/createDeferredPromise.ts (1)
createDeferredPromise(11-19)packages/clerk-js/src/ui/components/OrganizationSwitcher/__tests__/test-utils.ts (3)
createFakeUserOrganizationMembership(97-114)createFakeUserOrganizationInvitation(65-88)createFakeUserOrganizationSuggestion(125-145)
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx (2)
packages/shared/src/utils/createDeferredPromise.ts (1)
createDeferredPromise(11-19)packages/clerk-js/src/ui/components/OrganizationProfile/__tests__/utils.ts (1)
createFakeOrganizationInvitation(91-106)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (5)
packages/clerk-js/src/test/create-fixtures.tsx (1)
2-2: LGTM! Stable SWR configuration improves test reliability.The use of
useStateto memoize theswrConfigobject ensures it remains stable across renders, preventing unnecessary cache invalidation in tests. This is a best practice for providing stable object references to context providers.Also applies to: 87-87, 111-111
packages/shared/src/react/hooks/usePagesOrInfinite.ts (1)
101-104: LGTM! Core fix for infinite pagination revalidation.Adding
revalidateFirstPage: falseto the infinite options correctly prevents SWR from refetching the first page when loading additional pages. This aligns with the PR objective and standard SWR infinite loading best practices.Also applies to: 257-257
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganization.test.tsx (3)
46-46: LGTM! Better test coverage with explicit non-call assertions.Adding assertions that organization methods are not called when pagination options aren't provided verifies the lazy-loading behavior of the hook. This is good defensive testing.
Also applies to: 70-73
76-77: LGTM! Enhanced null state verification.The assertion that
fixtures.clerk.organizationis null validates the fixture setup and makes the test more comprehensive. The updated test description is also clearer.Also applies to: 93-93
519-519: LGTM! Consistent deferred promise pattern.The test refactoring follows the same improved async control pattern as the other test file, ensuring consistent and reliable test behavior.
Also applies to: 554-578
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.test.tsx
Show resolved
Hide resolved
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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 (1)
packages/shared/src/react/hooks/usePagesOrInfinite.ts (1)
101-104: Consider adding a comment explainingrevalidateFirstPage: false.The implementation is correct and aligns with the PR objective to fix inconsistent infinite pagination behavior. However, given that this file includes detailed comments explaining complex caching logic (e.g., lines 172-229), consider adding a brief comment explaining why
revalidateFirstPage: falseis set. This would help future maintainers understand the rationale.Example:
+// Prevent revalidation of the first page when fetching subsequent pages (page 2+) +// to ensure consistent behavior across all infinite pagination fetches const cachingSWRInfiniteOptions = { ...cachingSWROptions, revalidateFirstPage: false, } satisfies Parameters<typeof useSWRInfinite>[2];
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/shared/src/react/hooks/usePagesOrInfinite.ts(2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/shared/src/react/hooks/usePagesOrInfinite.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/react/hooks/usePagesOrInfinite.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/shared/src/react/hooks/usePagesOrInfinite.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/shared/src/react/hooks/usePagesOrInfinite.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/shared/src/react/hooks/usePagesOrInfinite.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/shared/src/react/hooks/usePagesOrInfinite.ts (1)
257-257: LGTM! Correct application of infinite pagination configuration.The change correctly applies
cachingSWRInfiniteOptionsto theuseSWRInfinitehook while leaving the regularuseSWRcall (line 212) unchanged. This properly separates the configuration between paginated and infinite loading modes, ensuring therevalidateFirstPage: falsesetting only affects infinite pagination as intended.
Description
SWRInfinite revalidates the first page when fetching the second page, but stops there which makes the behaviour inconsistent compared to fetching the next pages (>=3). This PR addresses that and by disabling that behaviour.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Tests
Refactor
Chores