Skip to content

fix: prevent stale cart cache after navigation - #527

Merged
KaiUweCZE merged 2 commits into
masterfrom
fix/cart-cache-navigation-race
Aug 1, 2026
Merged

fix: prevent stale cart cache after navigation#527
KaiUweCZE merged 2 commits into
masterfrom
fix/cart-cache-navigation-race

Conversation

@KaiUweCZE

@KaiUweCZE KaiUweCZE commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes
    • Improved cart data synchronisation after successful and failed updates.
    • Prevented stale cart information from replacing newer results.
    • Ensured restored or inactive cart views retain the latest available data.
    • Improved reliability when multiple cart updates occur in quick succession.

@vercel

vercel Bot commented Jul 31, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
new-engine-ui-storybook Ready Ready Preview Aug 1, 2026 8:32am

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ac1451d5-4b46-4a1f-8c44-e3ff5b213d39

📥 Commits

Reviewing files that changed from the base of the PR and between b30e8cf and f9dd05b.

📒 Files selected for processing (2)
  • libs/storefront-data/src/cart/hooks.ts
  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
📜 Recent review details
⚠️ CI failures not shown inline (1)

GitHub Check: Kilo Code Review: Kilo Code Review failed

Conclusion: failure

View job details

Review failed: The message could not be delivered
🧰 Additional context used
📓 Path-based instructions (6)
libs/storefront-data/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (libs/storefront-data/AGENTS.md)

libs/storefront-data/src/**/*.{ts,tsx}: Do not import from ./dist/ paths - use source files instead
Do not hardcode query keys - use createQueryKey() utility instead
Do not mix server and client code in the same file
Use cache strategies from CacheConfig (static, semiStatic, realtime, userData) for query configuration
Use TanStack Query 5+ for data fetching, caching, and SSR hydration in @techsio/storefront-data

Files:

  • libs/storefront-data/src/cart/hooks.ts
libs/storefront-data/**/*.{ts,tsx}

📄 CodeRabbit inference engine (libs/storefront-data/AGENTS.md)

Do not use any type - use proper generics instead

Medusa storefront data layer should use TanStack Query for data fetching in libs/storefront-data

Files:

  • libs/storefront-data/src/cart/hooks.ts
  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
libs/storefront-data/src/**/hooks.ts

📄 CodeRabbit inference engine (libs/storefront-data/AGENTS.md)

Always use factory pattern for hooks (e.g., createProductHooks, createCollectionHooks, etc.)

Files:

  • libs/storefront-data/src/cart/hooks.ts
libs/**

📄 CodeRabbit inference engine (AGENTS.md)

Use RSLib for building libraries in the monorepo

Files:

  • libs/storefront-data/src/cart/hooks.ts
  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Run Biome linting and formatting only on changed files using 'bunx biome check --write path/to/file'

Files:

  • libs/storefront-data/src/cart/hooks.ts
  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Vitest for running tests in backend and UI library projects

Files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
🧠 Learnings (1)
📚 Learning: 2025-12-16T19:45:17.746Z
Learnt from: BleedingDev
Repo: NMIT-WR/new-engine PR: 207
File: libs/ui/src/molecules/select.tsx:50-50
Timestamp: 2025-12-16T19:45:17.746Z
Learning: When reviewing Tailwind classes in TSX/TS files, prefer using square brackets for arbitrary CSS values and complex expressions. Specifically: - Do not use the parentheses syntax (z-(--z-index)) for anything beyond simple CSS variable references; this syntax auto-wraps in var() and cannot handle calc or complex functions. - Use the square brackets syntax (e.g., h-[calc(var(--available-height)-var(--spacing-content))]) for calc expressions, var with calc, and any complex CSS expressions. This rule applies broadly to Tailwind v4 usage in TSX code across the project.

Applied to files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
🔇 Additional comments (4)
libs/storefront-data/src/cart/hooks.ts (3)

15-19: LGTM!

Also applies to: 537-549


624-653: LGTM!


767-770: LGTM!

Also applies to: 795-796, 829-830, 877-878, 910-911, 939-940, 968-969

libs/storefront-data/tests/cart.hooks.reactivity.test.tsx (1)

309-378: LGTM!


Walkthrough

Cart mutation synchronisation now cancels matching cart queries before applying results. Mutation success handlers await synchronisation. Cart alias propagation rejects stale source data. New tests cover mutation and observer reactivity races.

Changes

Cart cache protection

Layer / File(s) Summary
Mutation cache cancellation
libs/storefront-data/src/shared/cart-cache-sync.ts, libs/storefront-data/src/cart/hooks.ts
cancelCartCaches cancels matching active-cart and detail queries in parallel. Mutation success handlers await cache synchronisation before callbacks or completion.
Stale alias protection
libs/storefront-data/src/cart/hooks.ts
Cart aliases propagate only when the active source query still contains the returned cart object.
Reactivity regression coverage
libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
Tests cover mutation ordering, inactive observer restoration, stale reads, and active reads after failed mutations.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MutationHandler
  participant CartCacheSync
  participant QueryClient
  MutationHandler->>CartCacheSync: synchronise mutation cart
  CartCacheSync->>QueryClient: cancel matching cart queries
  QueryClient-->>CartCacheSync: cancellation complete
  CartCacheSync-->>MutationHandler: synchronisation complete
  MutationHandler->>MutationHandler: invoke success callback
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: preventing stale cart cache data after navigation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cart-cache-navigation-race
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/cart-cache-navigation-race

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

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

The PR coordinates cart-query cancellation and cache synchronization to preserve the newest cart state.

  • Starts cancellation before synchronously publishing mutation results, preventing delayed cancellation from reordering mutation writes.
  • Guards cache fan-out so restored inactive observers cannot propagate stale data.
  • Adds regression coverage for overlapping mutations, stale reads, inactive observers, and failed mutations.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
libs/storefront-data/src/cart/hooks.ts Reorders mutation cache synchronization and adds an ownership guard before cart data fans out to cache aliases.
libs/storefront-data/src/shared/cart-cache-sync.ts Adds a shared helper that silently cancels active and detail queries for a cart.
libs/storefront-data/tests/cart.hooks.reactivity.test.tsx Adds focused regression tests covering mutation ordering and stale cart-read synchronization.

Sequence Diagram

sequenceDiagram
  participant M as Cart mutation
  participant Q as QueryClient
  participant C as Cart consumers
  M->>Q: Start cancelCartCaches
  M->>Q: syncCartCaches(new cart)
  Q-->>C: Publish current cart
  M->>Q: Optionally invalidate caches
  Q-->>M: Cancellation settles
Loading

Reviews (2): Last reviewed commit: "fix(storefront-data): prevent stale cart..." | Re-trigger Greptile

Comment thread libs/storefront-data/src/cart/hooks.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
libs/storefront-data/src/cart/hooks.ts (1)

619-648: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

fix(cart): make syncCartCache safe for select consumers

syncCartCache compares the select-transformed cart with the raw cached query data. A transforming select can make this reference check fail while the hook still owns the active cache, which skips cache fan-out and stale query cleanup. Track ownership by a select-independent signal, such as stored query state metadata, and update the same check in useSuspenseCart.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/storefront-data/src/cart/hooks.ts` around lines 619 - 648, Update
syncCartCache and the corresponding ownership check in useSuspenseCart to avoid
comparing select-transformed cart references with raw query data; use
select-independent query state metadata to confirm the hook still owns the
active cache before fan-out and stale-query cleanup. Add or update coverage in
libs/storefront-data/tests/cart.hooks.reactivity.test.tsx:309-369 for
transformed select consumers, with no direct change required elsewhere.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@libs/storefront-data/src/cart/hooks.ts`:
- Around line 537-544: Update syncMutationCart to handle cancelCartCaches
failures independently: catch and contain errors from cache cancellation, then
continue running syncCartCaches, invalidateCart, and the caller’s onSuccess flow
even when cancellation rejects. Keep the mutation success result unaffected by
cache-sync failures.

---

Outside diff comments:
In `@libs/storefront-data/src/cart/hooks.ts`:
- Around line 619-648: Update syncCartCache and the corresponding ownership
check in useSuspenseCart to avoid comparing select-transformed cart references
with raw query data; use select-independent query state metadata to confirm the
hook still owns the active cache before fan-out and stale-query cleanup. Add or
update coverage in
libs/storefront-data/tests/cart.hooks.reactivity.test.tsx:309-369 for
transformed select consumers, with no direct change required elsewhere.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4d989c40-dec7-4e8b-846c-9c15b2e3dc58

📥 Commits

Reviewing files that changed from the base of the PR and between 2b119a8 and b30e8cf.

📒 Files selected for processing (3)
  • libs/storefront-data/src/cart/hooks.ts
  • libs/storefront-data/src/shared/cart-cache-sync.ts
  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: main
  • GitHub Check: Greptile Review
⚠️ CI failures not shown inline (1)

GitHub Check: Kilo Code Review: Kilo Code Review failed

Conclusion: failure

View job details

Review failed: The message could not be delivered
🧰 Additional context used
📓 Path-based instructions (6)
libs/storefront-data/**/*.{ts,tsx}

📄 CodeRabbit inference engine (libs/storefront-data/AGENTS.md)

Do not use any type - use proper generics instead

Medusa storefront data layer should use TanStack Query for data fetching in libs/storefront-data

Files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
  • libs/storefront-data/src/shared/cart-cache-sync.ts
  • libs/storefront-data/src/cart/hooks.ts
libs/**

📄 CodeRabbit inference engine (AGENTS.md)

Use RSLib for building libraries in the monorepo

Files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
  • libs/storefront-data/src/shared/cart-cache-sync.ts
  • libs/storefront-data/src/cart/hooks.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Vitest for running tests in backend and UI library projects

Files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Run Biome linting and formatting only on changed files using 'bunx biome check --write path/to/file'

Files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
  • libs/storefront-data/src/shared/cart-cache-sync.ts
  • libs/storefront-data/src/cart/hooks.ts
libs/storefront-data/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (libs/storefront-data/AGENTS.md)

libs/storefront-data/src/**/*.{ts,tsx}: Do not import from ./dist/ paths - use source files instead
Do not hardcode query keys - use createQueryKey() utility instead
Do not mix server and client code in the same file
Use cache strategies from CacheConfig (static, semiStatic, realtime, userData) for query configuration
Use TanStack Query 5+ for data fetching, caching, and SSR hydration in @techsio/storefront-data

Files:

  • libs/storefront-data/src/shared/cart-cache-sync.ts
  • libs/storefront-data/src/cart/hooks.ts
libs/storefront-data/src/**/hooks.ts

📄 CodeRabbit inference engine (libs/storefront-data/AGENTS.md)

Always use factory pattern for hooks (e.g., createProductHooks, createCollectionHooks, etc.)

Files:

  • libs/storefront-data/src/cart/hooks.ts
🧠 Learnings (1)
📚 Learning: 2025-12-16T19:45:17.746Z
Learnt from: BleedingDev
Repo: NMIT-WR/new-engine PR: 207
File: libs/ui/src/molecules/select.tsx:50-50
Timestamp: 2025-12-16T19:45:17.746Z
Learning: When reviewing Tailwind classes in TSX/TS files, prefer using square brackets for arbitrary CSS values and complex expressions. Specifically: - Do not use the parentheses syntax (z-(--z-index)) for anything beyond simple CSS variable references; this syntax auto-wraps in var() and cannot handle calc or complex functions. - Use the square brackets syntax (e.g., h-[calc(var(--available-height)-var(--spacing-content))]) for calc expressions, var with calc, and any complex CSS expressions. This rule applies broadly to Tailwind v4 usage in TSX code across the project.

Applied to files:

  • libs/storefront-data/tests/cart.hooks.reactivity.test.tsx
🔇 Additional comments (5)
libs/storefront-data/src/shared/cart-cache-sync.ts (1)

208-229: LGTM!

libs/storefront-data/src/cart/hooks.ts (2)

15-19: LGTM!


762-764: LGTM!

Also applies to: 790-791, 824-825, 872-873, 905-906, 934-935, 963-964

libs/storefront-data/tests/cart.hooks.reactivity.test.tsx (2)

371-447: LGTM!


449-519: LGTM!

Comment thread libs/storefront-data/src/cart/hooks.ts
@KaiUweCZE
KaiUweCZE merged commit 62b261c into master Aug 1, 2026
6 of 7 checks passed
@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown

🎉 This PR is included in version 0.30.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant