-
Notifications
You must be signed in to change notification settings - Fork 382
fix(clerk-js, shared): Auto revalidate hook on mutations #6702
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
base: main
Are you sure you want to change the base?
fix(clerk-js, shared): Auto revalidate hook on mutations #6702
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds a new internal event channel resource:action across types and event bus, exposes the public event bus via a Clerk getter, emits events from checkout confirm and subscription item cancel, forwards listeners in IsomorphicClerk, introduces a throttled React event hook, refactors useSubscription to revalidate on these events, and removes subscriptions revalidation from Plans. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant UI as UI / Components
participant Checkout as CommerceCheckout.confirm
participant Clerk as Clerk.__internal_eventBus
participant Iso as IsomorphicClerk
participant Hook as useThrottledEvent listener
participant Sub as useSubscription (SWR)
participant API as clerk.billing.getSubscription
User->>UI: Confirm checkout
UI->>Checkout: confirm(params)
Checkout->>Checkout: await retry(...)
Checkout-->>Clerk: emit('resource:action', 'checkout.confirm')
Note right of Clerk: New event channel
Clerk-->>Iso: forward listener notification
Iso-->>Hook: notify 'checkout.confirm'
Hook->>Sub: trigger revalidate (throttled by key)
Sub->>API: fetch subscription
API-->>Sub: data
Sub-->>UI: updated subscription state
sequenceDiagram
autonumber
participant UI as UI / Components
participant Item as CommerceSubscriptionItem.cancel
participant Clerk as Clerk.__internal_eventBus
participant Iso as IsomorphicClerk
participant Hook as useThrottledEvent listener
participant Sub as useSubscription (SWR)
UI->>Item: cancel()
Item->>Item: DELETE → json
Item-->>Clerk: emit('resource:action', 'subscriptionItem.cancel')
Clerk-->>Iso: forward listener notification
Iso-->>Hook: notify 'subscriptionItem.cancel'
Hook->>Sub: revalidate (deduped)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
@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: 2
🧹 Nitpick comments (14)
packages/clerk-js/src/core/clerk.ts (1)
242-244
: Type the internal getter and document intentAdd an explicit return type and a brief JSDoc noting this is internal-only. This keeps the public surface typed while signaling non-API status.
- get __internal_eventBus() { - return this.#publicEventBus; - } + /** + * INTERNAL: exposed for cross-package wiring (not a supported public API). + * Do not rely on this outside Clerk-owned packages. + */ + get __internal_eventBus(): ReturnType<typeof createClerkEventBus> { + return this.#publicEventBus; + }packages/types/src/clerk.ts (1)
152-153
: Centralize resource action literals into a named typeDefining a reusable alias improves discoverability and future extension (add actions in one place).
export type ClerkEventPayload = { status: ClerkStatus; - 'resource:action': 'checkout.confirm' | 'subscriptionItem.cancel'; + 'resource:action': ClerkResourceAction; };Add near the other top-level type aliases (outside this hunk):
export type ClerkResourceAction = 'checkout.confirm' | 'subscriptionItem.cancel';packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)
120-121
: Guard the internal bus access; add explicit return type (optional)Avoid a rare NPE if BaseResource.clerk isn’t populated, and consider annotating the method’s return type.
- CommerceSubscription.clerk.__internal_eventBus.emit('resource:action', 'subscriptionItem.cancel'); + CommerceSubscription.clerk?.__internal_eventBus?.emit('resource:action', 'subscriptionItem.cancel');Outside this hunk (optional):
public async cancel(params: CancelSubscriptionParams): Promise<DeletedObject> { ... }packages/react/src/isomorphicClerk.ts (1)
568-571
: Fix comment and use the event constantUse the shared constant to avoid typos; correct the comment reference.
- this.#eventBus.internal.retrieveListeners('resource:action')?.forEach(listener => { - // Since clerkjs exists it will call `this.clerkjs.on('status', listener)` - this.on('resource:action', listener, { notify: true }); - }); + this.#eventBus.internal.retrieveListeners(clerkEvents.ResourceAction)?.forEach(listener => { + // Since clerkjs exists it will call `this.clerkjs.on('resource:action', listener)` + this.on(clerkEvents.ResourceAction, listener, { notify: true }); + });packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
129-133
: Optional: batch the cache invalidations to avoid interleaved re-renders.Not critical, but batching avoids multiple state transitions when these resolve at slightly different times.
- const revalidateAll = useCallback(() => { - // Revalidate the plans - void revalidatePlans(); - void revalidateStatements(); - void revalidatePaymentSources(); - }, [revalidatePlans, revalidateStatements, revalidatePaymentSources]); + const revalidateAll = useCallback(async () => { + // Invalidate caches together + await Promise.all([revalidatePlans(), revalidateStatements(), revalidatePaymentSources()]); + }, [revalidatePlans, revalidateStatements, revalidatePaymentSources]);packages/clerk-js/src/core/resources/CommerceCheckout.ts (1)
60-86
: Comment vs behavior mismatch; avoidany
in request body.
- The retry comments (“up to 3 times”, “2s, 4s, 6s, 8s”) don’t match the config (cap at 2s, iterations check
>= 4
). Align the comment to the actual behavior or adjust the config.- Prefer a precise cast over
any
.- // Retry confirmation in case of a 500 error - // This will retry up to 3 times with an increasing delay - // It retries at 2s, 4s, 6s and 8s + // Retry on server errors or specific 409s. + // Retries up to 4 attempts with ~2s capped delay between attempts. ... - body: params as any, + body: params as ConfirmCheckoutParams,packages/shared/src/react/hooks/useThrottledEvent.tsx (4)
18-36
: Narrow theclerk
param to the minimal surface.Depending on a hook’s return type (
useClerkInstanceContext
) leaks an internal detail. Use a small interface to express what you need.-import type { useClerkInstanceContext } from '../contexts'; +type ClerkLike = { + on: (event: 'resource:action', handler: (payload: ClerkEventPayload['resource:action']) => void) => void; + off: (event: 'resource:action', handler: (payload: ClerkEventPayload['resource:action']) => void) => void; +}; ... - clerk: ReturnType<typeof useClerkInstanceContext>; + clerk: ClerkLike;
68-97
: Stale handler risk across shared keys.When multiple components share
uniqueKey
, the first registrant’shandler
is retained. If another component with the same key updatesonEvent
/events
, its changes won’t be reflected until the first unmounts. Consider referencing a mutable ref for the callback to avoid stale closures.-import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; ... + const onEventRef = useRef(onEvent); + onEventRef.current = onEvent; + if (existingEntry) { // Increment reference count for existing event listener existingEntry.refCount++; } else { ... - const handler = (payload: ClerkEventPayload['resource:action']) => { - if (events.includes(payload)) { - onEvent(payload); - } - }; + const handler = (payload: ClerkEventPayload['resource:action']) => { + // Use latest callback without re-binding the listener. + if (events.includes(payload)) { + onEventRef.current(payload); + } + };
84-90
: Handle Clerk instance swaps (SSR/hydration/HMR).If the
clerk
instance changes while other references keep the listener alive, the registry continues using the old instance. Track the instance and rebind when it changes.type ThrottledEventRegistry = { refCount: number; handler: (payload: ClerkEventPayload['resource:action']) => void; cleanup: () => void; + clerk: unknown; }; ... - // Register the event listener + // Register the event listener on('resource:action', handler); ... throttledEventRegistry.set(uniqueKey, { refCount: 1, handler, cleanup, + clerk, }); } // Cleanup function return () => { if (!uniqueKey) return; const entry = throttledEventRegistry.get(uniqueKey); if (entry) { + // If Clerk instance changed, rebind to the new one for the next registrant + if (entry.clerk !== clerk && entry.refCount > 0) { + entry.cleanup(); + const on = clerk.on.bind(clerk as any); + const off = clerk.off.bind(clerk as any); + on('resource:action', entry.handler); + entry.cleanup = () => off('resource:action', entry.handler); + entry.clerk = clerk; + } entry.refCount--;Also applies to: 99-115
79-82
: Micro: precompute membership for events.If
events
grows, a Set avoids repeated linear scans. Minor impact here.- const handler = (payload: ClerkEventPayload['resource:action']) => { - if (events.includes(payload)) { + const eventsSet = new Set(events); + const handler = (payload: ClerkEventPayload['resource:action']) => { + if (eventsSet.has(payload)) { onEvent(payload); } };packages/shared/src/react/hooks/useSubscription.tsx (4)
58-63
: Minor: avoid param shadowing to improve readabilityRename the fetcher param so it doesn’t shadow the outer
key
binding.- const swr = useSWR(key, key => clerk.billing.getSubscription(key.args), { + const swr = useSWR(key, swrKey => clerk.billing.getSubscription(swrKey.args), { dedupingInterval: 1_000 * 60, keepPreviousData: params?.keepPreviousData, revalidateOnFocus: false, });
2-2
: Prefer the stable mutate reference over wrapping with useCallback
mutate
from SWR is already stable; you can avoid an extra closure and remove an unused React import.-import { useCallback, useMemo } from 'react'; +import { useMemo } from 'react';- const revalidate = useCallback(() => swr.mutate(), [swr.mutate]); + const { mutate: revalidate } = swr;Also applies to: 64-64
66-69
: Comment typo and minor cleanupFix spelling and spacing.
- // `swr.mutate` does not dedupe, N parallel calles will fire N revalidation requests. - // To avoid this, we use `useThrottledEvent` to dedupe the revalidation requests. + // `swr.mutate` does not dedupe; N parallel calls will fire N revalidation requests. + // To avoid this, we use `useThrottledEvent` to dedupe the revalidation requests.
35-83
: Add an explicit return type for the public hookPer repo guidelines, public APIs should declare explicit return types. Define and export a
UseSubscriptionResult
type (using your canonical Subscription type) and annotateuseSubscription
.If you want, I can draft the exact type using your
@clerk/types
Subscription shape and the SWR wrapper’sMutate
type.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (9)
packages/clerk-js/src/core/clerk.ts
(1 hunks)packages/clerk-js/src/core/resources/CommerceCheckout.ts
(2 hunks)packages/clerk-js/src/core/resources/CommerceSubscription.ts
(1 hunks)packages/clerk-js/src/ui/contexts/components/Plans.tsx
(2 hunks)packages/react/src/isomorphicClerk.ts
(1 hunks)packages/shared/src/clerkEventBus.ts
(1 hunks)packages/shared/src/react/hooks/useSubscription.tsx
(4 hunks)packages/shared/src/react/hooks/useThrottledEvent.tsx
(1 hunks)packages/types/src/clerk.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/clerkEventBus.ts
packages/clerk-js/src/core/clerk.ts
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/types/src/clerk.ts
packages/clerk-js/src/core/resources/CommerceCheckout.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.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/shared/src/clerkEventBus.ts
packages/clerk-js/src/core/clerk.ts
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/types/src/clerk.ts
packages/clerk-js/src/core/resources/CommerceCheckout.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/clerkEventBus.ts
packages/clerk-js/src/core/clerk.ts
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/types/src/clerk.ts
packages/clerk-js/src/core/resources/CommerceCheckout.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/shared/src/clerkEventBus.ts
packages/clerk-js/src/core/clerk.ts
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/types/src/clerk.ts
packages/clerk-js/src/core/resources/CommerceCheckout.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/clerkEventBus.ts
packages/clerk-js/src/core/clerk.ts
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/types/src/clerk.ts
packages/clerk-js/src/core/resources/CommerceCheckout.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.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/shared/src/clerkEventBus.ts
packages/clerk-js/src/core/clerk.ts
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/types/src/clerk.ts
packages/clerk-js/src/core/resources/CommerceCheckout.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.tsx
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/contexts/components/Plans.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/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.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/contexts/components/Plans.tsx
packages/shared/src/react/hooks/useThrottledEvent.tsx
packages/shared/src/react/hooks/useSubscription.tsx
🧬 Code graph analysis (4)
packages/clerk-js/src/core/resources/CommerceCheckout.ts (1)
packages/types/src/commerce.ts (1)
ConfirmCheckoutParams
(1184-1210)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
packages/shared/src/react/hooks/useSubscription.tsx (1)
useSubscription
(35-83)
packages/shared/src/react/hooks/useThrottledEvent.tsx (1)
packages/types/src/clerk.ts (1)
ClerkEventPayload
(150-153)
packages/shared/src/react/hooks/useSubscription.tsx (3)
packages/types/src/clerk.ts (1)
ClerkEventPayload
(150-153)packages/react/src/isomorphicClerk.ts (2)
user
(689-695)organization
(697-703)packages/shared/src/react/hooks/useThrottledEvent.tsx (1)
useThrottledEvent
(63-115)
⏰ 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). (7)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: triage
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (6)
packages/shared/src/clerkEventBus.ts (1)
7-8
: LGTM: event key added and typed correctlyThe new ResourceAction key aligns with ClerkEventPayload and preserves type safety.
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
118-118
: Verified:useSubscription
listens to bothcheckout.confirm
andsubscriptionItem.cancel
viauseThrottledEvent
.packages/clerk-js/src/core/resources/CommerceCheckout.ts (2)
88-89
: Emit-on-success looks good.Event is only emitted after a successful confirm, which avoids false-positive revalidations. No changes needed.
56-56
: Public API:confirm
changed to async Update its JSDoc to returnPromise<this>
, and audit all downstream call sites and documentation to ensure callers nowawait
or handle the returned promise.packages/shared/src/react/hooks/useSubscription.tsx (2)
1-2
: Type-only imports look correctUsing
import type { ... }
and narrowing React imports is good.
26-26
: Event triggers are correctly scopedThe event list matches the declared union in types and keeps the hook focused on pertinent mutations.
const key = useMemo( | ||
() => | ||
user?.id | ||
? { | ||
type: 'commerce-subscription', | ||
userId: user.id, | ||
args: { orgId: params?.for === 'organization' ? organization?.id : undefined }, | ||
} | ||
: null, | ||
[user?.id, organization?.id, params?.for], | ||
); |
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.
🛠️ Refactor suggestion
Don’t fetch before org context is ready (prevents wrong-target queries)
When params?.for === 'organization'
but organization?.id
is not yet available, the hook still returns a non-null SWR key and calls getSubscription({ orgId: undefined })
. Gate the key until organization.id
exists to avoid misrouted or failing requests.
Apply:
- const key = useMemo(
- () =>
- user?.id
- ? {
- type: 'commerce-subscription',
- userId: user.id,
- args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
- }
- : null,
- [user?.id, organization?.id, params?.for],
- );
+ const key = useMemo(() => {
+ if (!user?.id) return null;
+ const isOrg = params?.for === 'organization';
+ if (isOrg && !organization?.id) return null;
+ return {
+ type: 'commerce-subscription' as const,
+ userId: user.id,
+ args: isOrg ? { orgId: organization!.id } : {},
+ };
+ }, [user?.id, organization?.id, params?.for]);
📝 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.
const key = useMemo( | |
() => | |
user?.id | |
? { | |
type: 'commerce-subscription', | |
userId: user.id, | |
args: { orgId: params?.for === 'organization' ? organization?.id : undefined }, | |
} | |
: null, | |
[user?.id, organization?.id, params?.for], | |
); | |
const key = useMemo(() => { | |
if (!user?.id) return null; | |
const isOrg = params?.for === 'organization'; | |
if (isOrg && !organization?.id) return null; | |
return { | |
type: 'commerce-subscription' as const, | |
userId: user.id, | |
args: isOrg ? { orgId: organization.id } : {}, | |
}; | |
}, [user?.id, organization?.id, params?.for]); |
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useSubscription.tsx around lines 44 to 54,
the SWR key is created even when params?.for === 'organization' but
organization?.id is not yet available, which causes getSubscription to be called
with orgId: undefined; change the useMemo so it returns null when the user is
missing or when params?.for === 'organization' and organization?.id is
falsy—i.e., gate the key on organization?.id existence—so SWR won't fetch until
the org context is ready; ensure the dependency array still includes user?.id,
organization?.id, and params?.for.
const serializedKey = useMemo(() => JSON.stringify(key), [key]); | ||
|
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.
Fix “null” uniqueKey leak into event registry
JSON.stringify(null)
is the string "null"
, which is truthy. This registers a shared listener for all not-ready hooks, wasting work and risking cross-instance coupling. Return undefined
when the key is null so useThrottledEvent
skips registration.
- const serializedKey = useMemo(() => JSON.stringify(key), [key]);
+ const serializedKey = useMemo(() => (key ? JSON.stringify(key) : undefined), [key]);
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useSubscription.tsx around lines 56 to 57,
JSON.stringify(key) currently turns a null key into the string "null" which
causes a shared listener to be registered; change the memo so that when key is
null or undefined it returns undefined (not the string "null") and otherwise
returns the JSON string—this ensures useThrottledEvent will skip registration
for not-ready hooks.
Description
Issue
Currently, when users perform actions like confirming checkouts or canceling subscriptions, the UI doesn't automatically reflect these changes. Users need to manually refresh or navigate away and back to see updated data, leading to a poor user experience.
Solution
The proposed solution automatically revalidates data when relevant mutation occur, and deduplicates event listeners to avoid multiple parallel revalidation requests.
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit