fix(broadcast-client): handle unhandled postMessage rejections #10771
main fromrefs/pull/10771/head·merged by TkDodo View on GitHubSummary#
Fixes #10543
broadcastQueryClient calls channel.postMessage() three times (on updated, removed, added) without .catch()-ing the returned promise. When query data contains a non-cloneable value (ReadableStream, Response, File, functions, Vue/MobX reactive proxies, etc.), the rejection becomes an unhandled DataCloneError with a stack pointing into node_modules — effectively unactionable in Sentry/Datadog.
Changes#
- Wrap all
channel.postMessage()calls in asafePost()helper that catches rejections - Add optional
onBroadcastErrorcallback toBroadcastQueryClientOptionsso consumers can route errors to their own error tracker with the offendingqueryHash - Fall back to
console.warnin development whenonBroadcastErroris not provided - Silent in production (no unhandled rejection, no console noise)
Usage#
broadcastQueryClient({
queryClient,
broadcastChannel: 'my-app',
onBroadcastError: (error, message) => {
Sentry.captureException(error, {
extra: { queryHash: message.queryHash, type: message.type },
})
},
})
Test plan#
-
onBroadcastErroris called with the error and message whenpostMessagerejects -
console.warnis emitted in development when noonBroadcastErroris provided - No warning in production when
postMessagefails - Existing tests still pass
- ESLint passes
🤖 Generated with Claude Code
Summary by CodeRabbit#
Bug Fixes
- Prevented unhandled rejections when cross-tab broadcasts fail due to non-serializable data.
- Failed synchronization now skips only the affected query while other broadcasts continue.
New Features
- Added an optional broadcast-error callback with event details for custom error reporting.
- Development builds provide console warnings when no error handler is configured.
- Reduced broadcast payload size for removed items.
Documentation
- Added guidance for handling broadcast errors.
Tests
- Expanded coverage for failures, callbacks, rejected handlers, and warnings.
- 1
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts (1)
60-78: ⚡ Quick winAdd a regression test for
onBroadcastErrorthrowing.Please add a case where
onBroadcastErrorthrows, and assert no unhandled rejection escapes. That protects the error-handling contract end-to-end.🤖 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 `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts` around lines 60 - 78, Add a test that simulates postMessage failing and the supplied onBroadcastError itself throwing: mockPostMessage to reject with the DOMException as before, pass an onBroadcastError mock that throws (e.g. throw new Error('boom')), register a temporary process.on('unhandledRejection') handler that fails the test if invoked, call broadcastQueryClient({ queryClient, broadcastChannel: 'test_channel', onBroadcastError }), trigger the broadcast via queryClient.setQueryData(['test'], { value: 1 }), await a microtask tick (e.g. setTimeout 0 or next tick), then remove the unhandledRejection handler and assert that onBroadcastError was called with the cloneError and that no unhandled rejection handler fired.🤖 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 `@packages/query-broadcast-client-experimental/src/index.ts`: - Around line 41-43: The postMessage rejection handler currently calls onBroadcastError(error, message) directly which can itself throw and convert the rejection handler into an unhandled rejection; update the catch path that contains the onBroadcastError invocation (in packages/query-broadcast-client-experimental/src/index.ts — the block that checks if (onBroadcastError) { onBroadcastError(error, message) } else if (process.env.NODE_ENV !== 'production') { ... }) to invoke onBroadcastError inside a local try/catch: call onBroadcastError(error, message) in the try, and if it throws swallow or log that secondary error (fallback to the existing console.warn behavior) so the original postMessage rejection handling remains safe and cannot be escalated by a throwing callback. --- Nitpick comments: In `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts`: - Around line 60-78: Add a test that simulates postMessage failing and the supplied onBroadcastError itself throwing: mockPostMessage to reject with the DOMException as before, pass an onBroadcastError mock that throws (e.g. throw new Error('boom')), register a temporary process.on('unhandledRejection') handler that fails the test if invoked, call broadcastQueryClient({ queryClient, broadcastChannel: 'test_channel', onBroadcastError }), trigger the broadcast via queryClient.setQueryData(['test'], { value: 1 }), await a microtask tick (e.g. setTimeout 0 or next tick), then remove the unhandledRejection handler and assert that onBroadcastError was called with the cloneError and that no unhandled rejection handler fired.🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID:
52ee48f6-f465-4bac-8951-d52f60b62ab6📥 Commits
Reviewing files that changed from the base of the PR and between ba6e7beebd50143408f01fcf5d9aee2ec1486f60 and 0893f0d95892512df2a6fb57444b7ca4951530ee.
📒 Files selected for processing (3)
.changeset/fix-broadcast-client-unhandled-rejection.mdpackages/query-broadcast-client-experimental/src/__tests__/index.test.tspackages/query-broadcast-client-experimental/src/index.ts
packages/query-broadcast-client-experimental/src/index.ts lines 77 to 94OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -27,3 +36,8 @@27362837 const queryCache = queryClient.getQueryCache()293839+ const safePost = (message: BroadcastMessage) => {40+ channel.postMessage(message).catch((error: unknown) => {41+ if (onBroadcastError) {42+ onBroadcastError(error, message)43+ } else if (process.env.NODE_ENV !== 'production') {⚠️ Potential issue | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail # Locate and show relevant portion of the file FILE="packages/query-broadcast-client-experimental/src/index.ts" if [ ! -f "$FILE" ]; then echo "Missing file: $FILE" >&2 exit 1 fi echo "---- File: $FILE (lines 1-120) ----" nl -ba "$FILE" | sed -n '1,140p' echo "---- Search for onBroadcastError ----" rg -n "onBroadcastError" "$FILE" || true echo "---- Extract safePost block ----" # Try to extract around safePost definition rg -n "safePost" "$FILE" || true # Print a window around first safePost match LINE="$(rg -n "const safePost" "$FILE" | head -n1 | cut -d: -f1 || true)" if [ -n "${LINE:-}" ]; then START=$((LINE-30)); END=$((LINE+80)) nl -ba "$FILE" | sed -n "${START},${END}p" fiRepository: TanStack/query
Length of output: 208
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" echo "---- Find calls to safePost ----" rg -n "safePost\(" "$FILE" || true echo "---- Show surrounding code where safePost is used ----" # For each match, print context rg -n "safePost\(" "$FILE" | while read -r match; do LINE="$(echo "$match" | cut -d: -f1)" START=$((LINE-20)); END=$((LINE+20)) echo "## Context around line $LINE" nl -ba "$FILE" | sed -n "${START},${END}p" doneRepository: TanStack/query
Length of output: 294
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" nl -ba "$FILE" | sed -n '30,70p'Repository: TanStack/query
Length of output: 101
🏁 Script executed:
#!/bin/bash set -euo pipefail # Locate and show relevant portion of the file FILE="packages/query-broadcast-client-experimental/src/index.ts" if [ ! -f "$FILE" ]; then echo "Missing file: $FILE" >&2 exit 1 fi echo "---- File: $FILE (lines 1-140) ----" nl -ba "$FILE" | sed -n '1,140p' echo "---- Search for onBroadcastError ----" rg -n "onBroadcastError" "$FILE" || true echo "---- Extract safePost block ----" # Try to extract around safePost definition rg -n "safePost" "$FILE" || true # Print a window around first safePost match LINE="$(rg -n "const safePost" "$FILE" | head -n1 | cut -d: -f1 || true)" if [ -n "${LINE:-}" ]; then START=$((LINE-30)); END=$((LINE+80)) nl -ba "$FILE" | sed -n "${START},${END}p" fiRepository: TanStack/query
Length of output: 208
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" if [ ! -f "$FILE" ]; then echo "Missing file: $FILE" >&2 exit 1 fi fmt_lines() { # usage: fmt_lines START END local s="${1:-1}" e="${2:-200}" awk -v s="$s" -v e="$e" '{if(NR>=s && NR<=e) printf "%6d\t%s\n", NR, $0 }' "$FILE" } echo "---- File: $FILE (lines 1-180) ----" fmt_lines 1 180 echo "---- Search for onBroadcastError ----" rg -n "onBroadcastError" "$FILE" || true echo "---- Search for safePost definition ----" rg -n "const safePost" "$FILE" || true echo "---- Extract safePost block (around const safePost) ----" LINE="$(rg -n "const safePost" "$FILE" | head -n1 | cut -d: -f1 || true)" if [ -n "${LINE:-}" ]; then START=$((LINE-40)); END=$((LINE+120)) if [ "$START" -lt 1 ]; then START=1; fi fmt_lines "$START" "$END" fi echo "---- Find calls to safePost ----" rg -n "safePost\(" "$FILE" || true echo "---- Context around each safePost call ----" rg -n "safePost\(" "$FILE" | while read -r match; do LINE="$(echo "$match" | cut -d: -f1)" START=$((LINE-15)); END=$((LINE+15)) if [ "$START" -lt 1 ]; then START=1; fi echo "## Context around line $LINE" fmt_lines "$START" "$END" doneRepository: TanStack/query
Length of output: 10944
Guard
onBroadcastErrorso its throw can’t turn thepostMessagerejection handler into an unhandled rejection.In
packages/query-broadcast-client-experimental/src/index.ts(safePost.catcharound theonBroadcastError(error, message)call), wrap the callback invocation in a localtry/catchand keep the fallback warning best-effort.Proposed fix
const safePost = (message: BroadcastMessage) => { channel.postMessage(message).catch((error: unknown) => { - if (onBroadcastError) { - onBroadcastError(error, message) - } else if (process.env.NODE_ENV !== 'production') { - console.warn( - `[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`, - error, - ) - } + if (onBroadcastError) { + try { + onBroadcastError(error, message) + return + } catch (callbackError) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `[broadcastQueryClient] onBroadcastError threw while handling "${message.type}" for queryHash "${message.queryHash}":`, + callbackError, + ) + } + return + } + } + + if (process.env.NODE_ENV !== 'production') { + console.warn( + `[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`, + error, + ) + } }) }📝 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 change77+ const safePost = (message: BroadcastMessage) => {78+ channel.postMessage(message).catch((error: unknown) => {79+ if (onBroadcastError) {80+ try {81+ onBroadcastError(error, message)82+ return83+ } catch (callbackError) {84+ if (process.env.NODE_ENV !== 'production') {85+ console.warn(86+ `[broadcastQueryClient] onBroadcastError threw while handling "${message.type}" for queryHash "${message.queryHash}":`,87+ callbackError,88+ )89+ }90+ return91+ }92+ }93+94+ if (process.env.NODE_ENV !== 'production') {95+ console.warn(96+ `[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`,97+ error,98+ )99+ }100+ })101+ }🤖 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 `@packages/query-broadcast-client-experimental/src/index.ts` around lines 41 - 43, The postMessage rejection handler currently calls onBroadcastError(error, message) directly which can itself throw and convert the rejection handler into an unhandled rejection; update the catch path that contains the onBroadcastError invocation (in packages/query-broadcast-client-experimental/src/index.ts — the block that checks if (onBroadcastError) { onBroadcastError(error, message) } else if (process.env.NODE_ENV !== 'production') { ... }) to invoke onBroadcastError inside a local try/catch: call onBroadcastError(error, message) in the try, and if it throws swallow or log that secondary error (fallback to the existing console.warn behavior) so the original postMessage rejection handling remains safe and cannot be escalated by a throwing callback.✅ Addressed in commit 71ceeea
Fixed in the latest commit (71ceeeaf2). Wrapped
onBroadcastErrorin atry/catchso that if the callback itself throws, the error is swallowed (with aconsole.warnfallback in dev) rather than escaping as an unhandled rejection. Also added a test asserting nounhandledRejectionfires when the callback throws. Thanks for the catch!@n-satoshi061, great fix! Thetry/catchwrapper aroundonBroadcastErrorensures the callback's own exceptions are contained, and the additional test covering the throwing-callback scenario gives solid coverage. The implementation in the file looks exactly right. 🐇✨
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts (1)
60-91: ⚡ Quick winAdd a regression test for rejected async handlers.
This test covers sync throw, but a Promise-rejecting
onBroadcastErrorpath is different and worth locking down with a dedicated case.Suggested additional test
+ it('should not cause an unhandled rejection when onBroadcastError returns a rejected promise', async () => { + const cloneError = new DOMException('DataCloneError', 'DataCloneError') + mockPostMessage.mockRejectedValueOnce(cloneError) + + const unhandledRejections: Array<unknown> = [] + const onUnhandledRejection = (reason: unknown) => { + unhandledRejections.push(reason) + } + process.on('unhandledRejection', onUnhandledRejection) + + const onBroadcastError = vi.fn().mockRejectedValue(new Error('boom-async')) + + try { + broadcastQueryClient({ + queryClient, + broadcastChannel: 'test_channel', + onBroadcastError, + }) + + queryClient.setQueryData(['test-async'], { value: 1 }) + await new Promise((r) => setTimeout(r, 0)) + + expect(onBroadcastError).toHaveBeenCalledWith( + cloneError, + expect.objectContaining({ type: 'added' }), + ) + expect(unhandledRejections).toHaveLength(0) + } finally { + process.off('unhandledRejection', onUnhandledRejection) + } + })🤖 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 `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts` around lines 60 - 91, Add a regression test that mirrors the existing "onBroadcastError throws" case but instead uses an async/rejecting handler: create an onBroadcastError stub that returns a rejected Promise (e.g. vi.fn().mockRejectedValue(new Error('boom'))), call broadcastQueryClient({ queryClient, broadcastChannel: 'test_channel', onBroadcastError }), trigger a broadcast via queryClient.setQueryData(['test'], { value: 1 }), capture process 'unhandledRejection' events into an array, wait a tick (setTimeout 0 or await Promise.resolve()) then assert the mock was called with the cloneError and expected message and that no unhandledRejections were recorded; reference onBroadcastError, broadcastQueryClient, and queryClient.setQueryData when locating where to add the test.🤖 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 `@packages/query-broadcast-client-experimental/src/index.ts`: - Around line 42-51: safePost currently calls onBroadcastError(...) inside a synchronous try/catch which misses async rejections; update safePost to capture the return value of onBroadcastError (e.g., const result = onBroadcastError(error, message)) and handle both sync and async errors by calling Promise.resolve(result).catch(err => { if (process.env.NODE_ENV !== 'production') console.warn(`[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`, err); }); so async callbacks are properly caught and logged without causing unhandledRejection. --- Nitpick comments: In `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts`: - Around line 60-91: Add a regression test that mirrors the existing "onBroadcastError throws" case but instead uses an async/rejecting handler: create an onBroadcastError stub that returns a rejected Promise (e.g. vi.fn().mockRejectedValue(new Error('boom'))), call broadcastQueryClient({ queryClient, broadcastChannel: 'test_channel', onBroadcastError }), trigger a broadcast via queryClient.setQueryData(['test'], { value: 1 }), capture process 'unhandledRejection' events into an array, wait a tick (setTimeout 0 or await Promise.resolve()) then assert the mock was called with the cloneError and expected message and that no unhandledRejections were recorded; reference onBroadcastError, broadcastQueryClient, and queryClient.setQueryData when locating where to add the test.🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID:
2357c389-bb7f-4815-9fcc-0db5fcf17887📥 Commits
Reviewing files that changed from the base of the PR and between 0893f0d95892512df2a6fb57444b7ca4951530ee and 71ceeeaf22dff7e439acf8884b2b79ff53aa49fd.
📒 Files selected for processing (2)
packages/query-broadcast-client-experimental/src/__tests__/index.test.tspackages/query-broadcast-client-experimental/src/index.ts
packages/query-broadcast-client-experimental/src/index.ts lines 87 to 92Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -27,3 +36,16 @@27362837 const queryCache = queryClient.getQueryCache()293839+ const safePost = (message: BroadcastMessage) => {40+ channel.postMessage(message).catch((error: unknown) => {41+ if (onBroadcastError) {42+ try {43+ onBroadcastError(error, message)44+ } catch {45+ if (process.env.NODE_ENV !== 'production') {46+ console.warn(47+ `[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`,48+ error,49+ )50+ }51+ }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
In TypeScript, can an async function be assigned to a callback type declared as returningvoid, and if its returned Promise rejects without a.catch, can that produce anunhandledRejection?💡 Result:
Yes—TypeScript will usually allow assigning an async function to a callback type declared as returning
void, because a contextual function type with return typevoiddoes not require the implementation to not return a value; any returned value (including a Promise from anasyncfunction) is ignored by the type system [1]. Example (type-checking permissive case): const cb: => void = async => { // ok await something; // if this throws/rejects... }; If that async function’s returned Promise rejects and there is no.catch(and nothingawaits it), then the rejection becomes an unhandled promise rejection at runtime. MDN notes that calling anasyncfunction returns a Promise that will be rejected if an exception is uncaught within the async function [2]. In Node.js, a rejected Promise without a handler can produceunhandledRejection(and modern Node defaults can even crash, depending on configuration) [3][4]. So, even though TypeScript types the callback as() => void, the underlying runtime behavior is still “fire-and-forget Promise”; if you don’t attach error handling, you can get an unhandled rejection. Practical implications: - TypeScript-eslint/no-misused-promisesflags “Promise-returning function provided where void expected” because leaving a dangling Promise can cause exactly this kind of issue [5]. - Fixes are to handle inside the callback (try/catch) or explicitly attach a rejection handler (e.g.,void fn().catch(...), or ensure the caller awaits/handles). If you share your exact callback signature and where it’s invoked (DOM event? Express handler? custom library?), I can show the safest pattern for that specific case.Citations:
- 1: https://www.typescriptlang.org/docs/handbook/2/functions.html
- 2: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
- 3: https://knowledgelib.io/software/debugging/nodejs-unhandled-promises/2026
- 4: https://oneuptime.com/blog/post/2026-01-25-fix-unhandled-promise-rejection-warning/view
- 5: https://github.com/typescript-eslint/typescript-eslint/issues/4619
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" echo "== File exists? ==" ls -l "$FILE" echo "== Lines 1-120 (for context) ==" nl -ba "$FILE" | sed -n '1,120p' echo "== Find onBroadcastError occurrences ==" rg -n "onBroadcastError" "$FILE" echo "== Show safePost implementation region (search for safePost or postMessage error handling) ==" rg -n "safePost|postMessage\\(" "$FILE"Repository: TanStack/query
Length of output: 277
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" echo "== File exists? ==" ls -l "$FILE" echo "== Lines 1-160 (for context) ==" nl -ba "$FILE" | sed -n '1,160p' echo "== Find onBroadcastError occurrences ==" rg -n "onBroadcastError" "$FILE" || true echo "== Show safePost implementation region ==" rg -n "safePost|postMessage\\(" "$FILE" || trueRepository: TanStack/query
Length of output: 277
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" echo "== File exists? ==" ls -l "$FILE" echo "== Lines 1-160 (for context) ==" nl -ba "$FILE" | sed -n '1,160p' echo "== Find onBroadcastError occurrences ==" rg -n "onBroadcastError" "$FILE" || true echo "== Show safePost implementation region ==" rg -n "safePost|postMessage\\(" "$FILE" || trueRepository: TanStack/query
Length of output: 277
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/query-broadcast-client-experimental/src/index.ts" echo "== File exists? ==" ls -l "$FILE" echo "== Lines 1-120 (for context) ==" awk 'NR>=1 && NR<=120 {printf "%4d %s\n", NR, $0}' "$FILE" echo "== Find onBroadcastError occurrences ==" rg -n "onBroadcastError" "$FILE" || true echo "== Show lines 30-90 (covers the previously referenced 42-51 region) ==" awk 'NR>=30 && NR<=90 {printf "%4d %s\n", NR, $0}' "$FILE" echo "== Show the type definition area (look for BroadcastQueryClientOptions) ==" rg -n "interface BroadcastQueryClientOptions|type BroadcastQueryClientOptions|onBroadcastError\\?:" "$FILE" || trueRepository: TanStack/query
Length of output: 6192
Handle rejected async
onBroadcastErrorcallbacks too.safePostonly wrapsonBroadcastError(...)in a synchronoustry/catch. If a consumer provides anasynconBroadcastError, any rejection occurs via the returned Promise and bypasses thiscatch, potentially causing anunhandledRejection.Proposed fix
interface BroadcastQueryClientOptions { queryClient: QueryClient broadcastChannel?: string options?: BroadcastChannelOptions - onBroadcastError?: (error: unknown, message: BroadcastMessage) => void + onBroadcastError?: ( + error: unknown, + message: BroadcastMessage, + ) => void | Promise<void> } @@ const safePost = (message: BroadcastMessage) => { channel.postMessage(message).catch((error: unknown) => { if (onBroadcastError) { try { - onBroadcastError(error, message) - } catch { + const callbackResult = onBroadcastError(error, message) + Promise.resolve(callbackResult).catch((callbackError: unknown) => { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `[broadcastQueryClient] onBroadcastError threw while handling "${message.type}" for queryHash "${message.queryHash}":`, + callbackError, + ) + } + }) + return + } catch (callbackError) { if (process.env.NODE_ENV !== 'production') { console.warn( - `[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`, - error, + `[broadcastQueryClient] onBroadcastError threw while handling "${message.type}" for queryHash "${message.queryHash}":`, + callbackError, ) } + return } } else if (process.env.NODE_ENV !== 'production') { console.warn( `[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`, error,🤖 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 `@packages/query-broadcast-client-experimental/src/index.ts` around lines 42 - 51, safePost currently calls onBroadcastError(...) inside a synchronous try/catch which misses async rejections; update safePost to capture the return value of onBroadcastError (e.g., const result = onBroadcastError(error, message)) and handle both sync and async errors by calling Promise.resolve(result).catch(err => { if (process.env.NODE_ENV !== 'production') console.warn(`[broadcastQueryClient] failed to broadcast "${message.type}" for queryHash "${message.queryHash}":`, err); }); so async callbacks are properly caught and logged without causing unhandledRejection.✅ Addressed in commit 062cba0
Thanks for catching this! Addressed in the latest commit:
- Updated
onBroadcastErrortype to(error, message) => void | Promise<void>to explicitly support async callbacks - In
safePost, captured the return value of the callback and added.catch()on it to handle async rejections - Extracted
warnBroadcastErrorhelper to deduplicate the warning logic - Added a test that verifies an async
onBroadcastErrorthat rejects does not produce an unhandled rejection
@n-satoshi061The implementation in the updated file looks great — all four cases are now properly handled:- Sync throw from
onBroadcastError→ caught bytry/catch, routed towarnBroadcastError - Async rejection from
onBroadcastError→ caught byresult?.catch(...), routed towarnBroadcastError - No callback provided →
warnBroadcastErrorcalled directly (dev-only warning) onBroadcastErrornot set → optional chaining onresult?.catchmeans no crash ifresultisundefined
The
warnBroadcastErrorrefactor is a nice cleanup too. Everything looks solid.(∩^o^)∩ 🐇✨
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
🧹 Nitpick comments (1)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts (1)
101-118: ⚡ Quick winEnsure the
unhandledRejectionlistener is always cleaned up.If this test throws before Line 117, the listener can leak into later tests. Wrap the body in
try/finallyand moveprocess.off(...)tofinally.Proposed fix
process.on('unhandledRejection', onUnhandledRejection) const onBroadcastError = vi .fn() .mockRejectedValueOnce(new Error('async boom')) - broadcastQueryClient({ - queryClient, - broadcastChannel: 'test_channel', - onBroadcastError, - }) - - queryClient.setQueryData(['test'], { value: 1 }) - - await new Promise((r) => setTimeout(r, 10)) - - process.off('unhandledRejection', onUnhandledRejection) - - expect(onBroadcastError).toHaveBeenCalledWith( - cloneError, - expect.objectContaining({ type: 'added' }), - ) - expect(unhandledRejections).toHaveLength(0) + try { + broadcastQueryClient({ + queryClient, + broadcastChannel: 'test_channel', + onBroadcastError, + }) + + queryClient.setQueryData(['test'], { value: 1 }) + + await new Promise((r) => setTimeout(r, 10)) + + expect(onBroadcastError).toHaveBeenCalledWith( + cloneError, + expect.objectContaining({ type: 'added' }), + ) + expect(unhandledRejections).toHaveLength(0) + } finally { + process.off('unhandledRejection', onUnhandledRejection) + }🤖 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 `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts` around lines 101 - 118, The test registers an unhandledRejection listener (onUnhandledRejection) but only removes it after awaited work, which can leak if the test throws; wrap the test body that calls broadcastQueryClient({ queryClient, broadcastChannel: 'test_channel', onBroadcastError }) and the subsequent queryClient.setQueryData/await in a try/finally and move process.off('unhandledRejection', onUnhandledRejection) into the finally block so the listener is always cleaned up even on failures; keep the same onBroadcastError mock and onUnhandledRejection setup/teardown structure.🤖 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. Nitpick comments: In `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts`: - Around line 101-118: The test registers an unhandledRejection listener (onUnhandledRejection) but only removes it after awaited work, which can leak if the test throws; wrap the test body that calls broadcastQueryClient({ queryClient, broadcastChannel: 'test_channel', onBroadcastError }) and the subsequent queryClient.setQueryData/await in a try/finally and move process.off('unhandledRejection', onUnhandledRejection) into the finally block so the listener is always cleaned up even on failures; keep the same onBroadcastError mock and onUnhandledRejection setup/teardown structure.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
f614ddbd-4a69-46da-979b-42cb682551ca📥 Commits
Reviewing files that changed from the base of the PR and between 71ceeeaf22dff7e439acf8884b2b79ff53aa49fd and 062cba086abc0432fd19f988553c5bde09fa22b7.
📒 Files selected for processing (2)
packages/query-broadcast-client-experimental/src/__tests__/index.test.tspackages/query-broadcast-client-experimental/src/index.ts
Fixed in the latest commit: wrapped both
unhandledRejectionlistener tests intry/finallysoprocess.off()is always called even if an assertion throws.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)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts (1)
163-204: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick winRestore
console.warnwithtry/finallyto avoid spy leakage.If an assertion fails before
mockRestore(), the spy can leak into later tests and cause cascading failures.Proposed fix
it('should warn in dev when postMessage fails and onBroadcastError is not provided', async () => { process.env['NODE_ENV'] = 'development' const cloneError = new DOMException('DataCloneError', 'DataCloneError') mockPostMessage.mockRejectedValueOnce(cloneError) const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - broadcastQueryClient({ - queryClient, - broadcastChannel: 'test_channel', - }) - - queryClient.setQueryData(['test'], { value: 1 }) - - await new Promise((r) => setTimeout(r, 0)) - expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining('cross-tab sync for this query was skipped'), - cloneError, - ) - - warnSpy.mockRestore() + try { + broadcastQueryClient({ + queryClient, + broadcastChannel: 'test_channel', + }) + + queryClient.setQueryData(['test'], { value: 1 }) + + await new Promise((r) => setTimeout(r, 0)) + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('cross-tab sync for this query was skipped'), + cloneError, + ) + } finally { + warnSpy.mockRestore() + } }) it('should not warn in production when postMessage fails', async () => { process.env['NODE_ENV'] = 'production' const cloneError = new DOMException('DataCloneError', 'DataCloneError') mockPostMessage.mockRejectedValueOnce(cloneError) const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - broadcastQueryClient({ - queryClient, - broadcastChannel: 'test_channel', - }) - - queryClient.setQueryData(['test'], { value: 1 }) - - await new Promise((r) => setTimeout(r, 0)) - expect(warnSpy).not.toHaveBeenCalled() - - warnSpy.mockRestore() + try { + broadcastQueryClient({ + queryClient, + broadcastChannel: 'test_channel', + }) + + queryClient.setQueryData(['test'], { value: 1 }) + + await new Promise((r) => setTimeout(r, 0)) + expect(warnSpy).not.toHaveBeenCalled() + } finally { + warnSpy.mockRestore() + } })🤖 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 `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts` around lines 163 - 204, Wrap the console.warn spy setup and assertions in a try/finally so the spy is always restored even if an assertion fails; specifically, in the two tests ("should warn in dev when postMessage fails and onBroadcastError is not provided" and "should not warn in production when postMessage fails") move the creation of warnSpy (vi.spyOn(console, 'warn').mockImplementation(() => {})) before the action, perform the broadcastQueryClient(...) and queryClient.setQueryData(...) and the expect(...) inside a try block, and call warnSpy.mockRestore() in the finally block to ensure the spy is cleaned up; keep references to mockPostMessage, broadcastQueryClient, queryClient, and warnSpy to locate the changes.🧹 Nitpick comments (2)
docs/framework/react/plugins/broadcastQueryClient.md (1)
35-37: ⚡ Quick winUpdate the API call snippet to reflect the new option.
The snippet still shows only
queryClientandbroadcastChannel; consider includingonBroadcastError(or...options) so the top-level API example matches the expanded options surface.Suggested doc tweak
-broadcastQueryClient({ queryClient, broadcastChannel }) +broadcastQueryClient({ queryClient, broadcastChannel, onBroadcastError })🤖 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 `@docs/framework/react/plugins/broadcastQueryClient.md` around lines 35 - 37, Update the top-level API snippet for broadcastQueryClient to show the new options surface by including the onBroadcastError option (or a spread like ...options) in the call signature; change the example invocation of broadcastQueryClient({ queryClient, broadcastChannel }) to include onBroadcastError (or ...options) so it matches the expanded options in the implementation and docs.packages/query-broadcast-client-experimental/src/__tests__/index.test.ts (1)
139-161: ⚡ Quick winAdd rejection-path coverage for
updatedandremovedevents.The new failure-path assertions currently validate only the
'added'event shape. SincesafePostis used across outbound message types, add one rejection test each for'updated'and'removed'to lock the event contract and prevent branch-specific regressions.🤖 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 `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts` around lines 139 - 161, Add rejection-path tests for the other message types: duplicate the existing test that mocks mockPostMessage to reject (using the same cloneError and mockRejectedValueOnce) and assert onBroadcastError is called with that error and an event object whose type is 'updated' (triggered by updating an existing query via queryClient.setQueryData on the same key) and another test where type is 'removed' (triggered by removing the query via queryClient.removeQueries or setting data to undefined). Use the same helpers used in the current test: mockPostMessage, broadcastQueryClient({... , onBroadcastError }), and expect.objectContaining<BroadcastErrorEvent> to validate queryHash and queryKey shape so the failure path of safePost is covered for 'updated' and 'removed'.🤖 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 `@packages/query-broadcast-client-experimental/src/index.ts`: - Line 19: Outbound "'added'" broadcast messages omit the source query state; update the message shape to include a state field and ensure creators populate it so receivers (the inbound 'added' handler that reads state) get the correct data. Specifically, extend the 'added' payload type to include state (alongside queryHash and queryKey) and modify the places that construct/send the 'added' message (the two sites flagged around the existing message constructors) to pass the source query's state (e.g., use the query's dehydrated/state value when building the message) so the emitter and receiver contracts match. --- Outside diff comments: In `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts`: - Around line 163-204: Wrap the console.warn spy setup and assertions in a try/finally so the spy is always restored even if an assertion fails; specifically, in the two tests ("should warn in dev when postMessage fails and onBroadcastError is not provided" and "should not warn in production when postMessage fails") move the creation of warnSpy (vi.spyOn(console, 'warn').mockImplementation(() => {})) before the action, perform the broadcastQueryClient(...) and queryClient.setQueryData(...) and the expect(...) inside a try block, and call warnSpy.mockRestore() in the finally block to ensure the spy is cleaned up; keep references to mockPostMessage, broadcastQueryClient, queryClient, and warnSpy to locate the changes. --- Nitpick comments: In `@docs/framework/react/plugins/broadcastQueryClient.md`: - Around line 35-37: Update the top-level API snippet for broadcastQueryClient to show the new options surface by including the onBroadcastError option (or a spread like ...options) in the call signature; change the example invocation of broadcastQueryClient({ queryClient, broadcastChannel }) to include onBroadcastError (or ...options) so it matches the expanded options in the implementation and docs. In `@packages/query-broadcast-client-experimental/src/__tests__/index.test.ts`: - Around line 139-161: Add rejection-path tests for the other message types: duplicate the existing test that mocks mockPostMessage to reject (using the same cloneError and mockRejectedValueOnce) and assert onBroadcastError is called with that error and an event object whose type is 'updated' (triggered by updating an existing query via queryClient.setQueryData on the same key) and another test where type is 'removed' (triggered by removing the query via queryClient.removeQueries or setting data to undefined). Use the same helpers used in the current test: mockPostMessage, broadcastQueryClient({... , onBroadcastError }), and expect.objectContaining<BroadcastErrorEvent> to validate queryHash and queryKey shape so the failure path of safePost is covered for 'updated' and 'removed'.🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID:
ac035baa-9615-4fe3-b1ba-af6c95bf3b11📥 Commits
Reviewing files that changed from the base of the PR and between 5b5339006a11ea8be53f801d9ee33a04e2a72b95 and ff1754938bad92eefd765a6247d68236dcf01d66.
📒 Files selected for processing (3)
docs/framework/react/plugins/broadcastQueryClient.mdpackages/query-broadcast-client-experimental/src/__tests__/index.test.tspackages/query-broadcast-client-experimental/src/index.ts
packages/query-broadcast-client-experimental/src/index.ts line 19OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1,3 +1,19 @@11 import { BroadcastChannel } from 'broadcast-channel'22 import type { BroadcastChannelOptions } from 'broadcast-channel'3-import type { QueryClient } from '@tanstack/query-core'3+import type { QueryClient, QueryKey } from '@tanstack/query-core'4+5+/**6+ * Metadata describing a broadcast that failed to be delivered to other tabs.7+ * Passed to {@link BroadcastQueryClientOptions.onBroadcastError} so callers8+ * can correlate failures with the originating query.9+ */10+export interface BroadcastErrorEvent {11+ type: 'updated' | 'removed' | 'added'12+ queryHash: string13+ queryKey: QueryKey14+}15+16+type BroadcastMessage =17+ | { type: 'updated'; queryHash: string; queryKey: QueryKey; state: unknown }18+ | { type: 'removed'; queryHash: string; queryKey: QueryKey }19+ | { type: 'added'; queryHash: string; queryKey: QueryKey }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Include
statein'added'broadcasts to match the receiver contract.The inbound
'added'handler consumesstate(Lines 167-179), but outbound'added'messages currently omit it. This can apply/build remote queries withundefinedstate instead of source state.Proposed fix
type BroadcastMessage = | { type: 'updated'; queryHash: string; queryKey: QueryKey; state: unknown } | { type: 'removed'; queryHash: string; queryKey: QueryKey } - | { type: 'added'; queryHash: string; queryKey: QueryKey } + | { type: 'added'; queryHash: string; queryKey: QueryKey; state: unknown } @@ if (queryEvent.type === 'added') { safePost({ type: 'added', queryHash, queryKey, + state, }) }Also applies to: 130-135
🤖 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 `@packages/query-broadcast-client-experimental/src/index.ts` at line 19, Outbound "'added'" broadcast messages omit the source query state; update the message shape to include a state field and ensure creators populate it so receivers (the inbound 'added' handler that reads state) get the correct data. Specifically, extend the 'added' payload type to include state (alongside queryHash and queryKey) and modify the places that construct/send the 'added' message (the two sites flagged around the existing message constructors) to pass the source query's state (e.g., use the query's dehydrated/state value when building the message) so the emitter and receiver contracts match.✅ Addressed in commits ff17549 to b32ff8e
Update summary#
After reviewing other PRs addressing the same issue (#10569, #10770, #10697) and the CodeRabbit feedback, I've made additional improvements beyond the initial unhandled-rejection fix. Here's a full summary of what's in the branch now.
Changes from the original PR#
Types
- Exported
BroadcastErrorEventinterface (withqueryKey: QueryKey) so consumers can import and reference the type directly:import type { BroadcastErrorEvent } from '@tanstack/query-broadcast-client-experimental' - Replaced the flat
BroadcastMessageinterface with a discriminated union —stateis now only present onupdatedandadded(notremoved), which matches the actual wire protocol onBroadcastErrornow receivesBroadcastErrorEvent(no internalstatefield) rather than the raw message objectonBroadcastErrorreturn type isvoid | Promise<void>to explicitly support async callbacks
Error handling in
safePostCase Behaviour postMessagerejectsonBroadcastErrorcalled with error + event; or devconsole.warnif no callbackonBroadcastErrorthrows synchronouslyCaught by try/catch; devconsole.warnwith callback erroronBroadcastErrorreturns a rejecting PromiseCaught by result?.catch(); devconsole.warnwith callback errorProduction, no callback Silent — no unhandled rejection, no console noise Warning messages
Two distinct messages to make debugging easier:
- Broadcast failure (no callback):
[broadcastQueryClient] Failed to broadcast "X" event for query Y. The query value could not be structured-cloned; cross-tab sync for this query was skipped. - Callback itself failed:
[broadcastQueryClient] onBroadcastError threw while handling "X" for query Y.
Bug fix:
statemissing from'added'broadcastsThe receiver's
onmessagehandler readsstateforaddedevents (query.setState(state)/queryCache.build(..., state)), but the sender was omitting it — causing receiving tabs to applyundefinedstate. Fixed by includingstatein the outboundaddedmessage and updating the discriminated union accordingly.Other
- Replaced
queryClient.getQueryCache().subscribe()withqueryCache.subscribe()(variable already in scope) - Added JSDoc to all
BroadcastQueryClientOptionsfields - Added "Handling broadcast errors" section to the docs with a Sentry example
CodeRabbit review responses#
Comment Resolution onBroadcastErrorthrowing causes a new unhandled rejectionWrapped callback in try/catch; added test asserting zerounhandledRejectionevents when callback throwsAsync onBroadcastErrorrejecting causes unhandled rejectionExtended type to void | Promise<void>; addedresult?.catch()guard; added test for async rejection path'added'broadcasts omitstate, breaking receiver contractAdded stateto theaddeddiscriminated union variant and to thesafePostcall site; confirmed with existing tests
Test coverage (9 tests)#
- subscribe / unsubscribe (existing)
onBroadcastErrorcalled whenpostMessagerejects- No unhandled rejection when callback throws synchronously
- Dev
console.warnemitted when callback throws (asserts message contains"onBroadcastError threw while handling") - No unhandled rejection when async callback rejects
- Dev
console.warnemitted when async callback rejects - Dev
console.warnemitted when no callback provided (asserts"cross-tab sync for this query was skipped") - No
console.warnin production
- Exported
@coderabbitai resume
✅ Actions performed
Reviews resumed.
Addressed in the latest commit (52d17622d).
All four tests that call
vi.spyOn(console, 'warn')now wrap their assertions intry/finallysomockRestore()is guaranteed to run even if an assertion fails — preventing the spy from leaking into subsequent tests.const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { // ...test body and assertions... } finally { warnSpy.mockRestore() }Applied to:
should warn in dev when onBroadcastError itself throwsshould warn in dev when async onBroadcastError rejectsshould warn in dev when postMessage fails and onBroadcastError is not providedshould not warn in production when postMessage fails
TkDodo approved these changes
Note
GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.
View your CI Pipeline Execution ↗ for commit 3e3623e2affd1352602bc7c1d9b0afc37078d91b
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 2m 50s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 40s View ↗
☁️ Nx Cloud last updated this comment at
2026-08-20 08:23:16UTCMore templates
- @tanstack/query-example-angular-auto-refetching
- @tanstack/query-example-angular-basic
- @tanstack/query-example-angular-basic-persister
- @tanstack/query-example-angular-devtools-panel
- @tanstack/query-example-angular-infinite-query-with-max-pages
- @tanstack/query-example-angular-optimistic-updates
- @tanstack/query-example-angular-pagination
- @tanstack/query-example-angular-query-options-from-a-service
- @tanstack/query-example-angular-router
- @tanstack/query-example-angular-rxjs
- @tanstack/query-example-angular-simple
- @tanstack/query-example-preact-simple
- @tanstack/query-example-lit-basic
- @tanstack/query-example-lit-pagination
- @tanstack/query-example-lit-ssr
- @tanstack/query-example-react-algolia
- @tanstack/query-example-react-auto-refetching
- @tanstack/query-example-react-basic
- @tanstack/query-example-react-basic-graphql-request
- @tanstack/query-example-chat
- @tanstack/query-example-react-default-query-function
- @tanstack/query-example-react-devtools-panel
- @tanstack/query-example-eslint-legacy
- @tanstack/query-example-eslint-plugin-demo
- @tanstack/query-example-react-infinite-query-with-max-pages
- @tanstack/query-example-react-load-more-infinite-scroll
- @tanstack/query-example-react-nextjs
- @tanstack/query-example-react-nextjs-app-optimistic-updates
- @tanstack/query-example-react-nextjs-app-prefetching
- @tanstack/query-example-nextjs-suspense-streaming
- @tanstack/query-example-react-offline
- @tanstack/query-example-react-pagination
- @tanstack/query-example-react-playground
- @tanstack/query-example-react-prefetching
- @tanstack/query-example-react-react-native
- @tanstack/query-example-react-router
- @tanstack/query-example-react-rick-morty
- @tanstack/query-example-react-shadow-dom
- @tanstack/query-example-react-simple
- @tanstack/query-example-react-star-wars
- @tanstack/query-example-react-suspense
- @tanstack/query-example-solid-astro
- @tanstack/query-example-solid-basic
- @tanstack/query-example-solid-basic-graphql-request
- @tanstack/query-example-solid-default-query-function
- @tanstack/query-example-solid-offline
- @tanstack/query-example-solid-simple
- @tanstack/query-example-solid-start-streaming
- @tanstack/query-example-svelte-auto-refetching
- @tanstack/query-example-svelte-basic
- @tanstack/query-example-svelte-load-more-infinite-scroll
- @tanstack/query-example-svelte-optimistic-updates
- @tanstack/query-example-svelte-playground
- @tanstack/query-example-svelte-simple
- @tanstack/query-example-svelte-ssr
- @tanstack/query-example-svelte-star-wars
- @tanstack/query-example-vue-2.6-basic
- @tanstack/query-example-vue-2.7-basic
- @tanstack/query-example-vue-basic
- @tanstack/query-example-vue-dependent-queries
- @tanstack/query-example-vue-nuxt3
- @tanstack/query-example-vue-persister
- @tanstack/query-example-vue-simple
@tanstack/angular-query-experimental
npm i https://pkg.pr.new/@tanstack/angular-query-experimental@10771@tanstack/eslint-plugin-query
npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@10771@tanstack/lit-query
npm i https://pkg.pr.new/@tanstack/lit-query@10771@tanstack/preact-query
npm i https://pkg.pr.new/@tanstack/preact-query@10771@tanstack/preact-query-devtools
npm i https://pkg.pr.new/@tanstack/preact-query-devtools@10771@tanstack/preact-query-persist-client
npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@10771@tanstack/query-async-storage-persister
npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@10771@tanstack/query-broadcast-client-experimental
npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@10771@tanstack/query-core
npm i https://pkg.pr.new/@tanstack/query-core@10771@tanstack/query-devtools
npm i https://pkg.pr.new/@tanstack/query-devtools@10771@tanstack/query-persist-client-core
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@10771@tanstack/query-sync-storage-persister
npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@10771@tanstack/react-query
npm i https://pkg.pr.new/@tanstack/react-query@10771@tanstack/react-query-devtools
npm i https://pkg.pr.new/@tanstack/react-query-devtools@10771@tanstack/react-query-next-experimental
npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@10771@tanstack/react-query-persist-client
npm i https://pkg.pr.new/@tanstack/react-query-persist-client@10771@tanstack/solid-query
npm i https://pkg.pr.new/@tanstack/solid-query@10771@tanstack/solid-query-devtools
npm i https://pkg.pr.new/@tanstack/solid-query-devtools@10771@tanstack/solid-query-persist-client
npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@10771@tanstack/svelte-query
npm i https://pkg.pr.new/@tanstack/svelte-query@10771@tanstack/svelte-query-devtools
npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@10771@tanstack/svelte-query-persist-client
npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@10771@tanstack/vue-query
npm i https://pkg.pr.new/@tanstack/vue-query@10771@tanstack/vue-query-devtools
npm i https://pkg.pr.new/@tanstack/vue-query-devtools@10771commit:
5f8172fTkDodo merged this3c79861
TkDodo closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
f6bcdf99-3e41-4fd2-a9de-8c771bf6854e📥 Commits
Reviewing files that changed from the base of the PR and between b0e7d7dca1d217197b8a784de415dfe5d6155414 and 3e3623e2affd1352602bc7c1d9b0afc37078d91b.
📒 Files selected for processing (1)
docs/framework/react/plugins/broadcastQueryClient.md🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
📝 Walkthrough
Walkthrough#
broadcastQueryClientnow routes rejectedBroadcastChannel.postMessagecalls throughsafePost. It supportsonBroadcastError, catches callback failures, and warns in development. Tests, documentation, and release metadata cover the behavior.Changes#
Broadcast error handling and recovery
packages/query-broadcast-client-experimental/src/index.tsBroadcastErrorEventand the optionalonBroadcastErrorcallback.packages/query-broadcast-client-experimental/src/index.tspackages/query-broadcast-client-experimental/src/index.tssafePost. Updated and added messages includestate; removed messages do not.packages/query-broadcast-client-experimental/src/__tests__/index.test.tsdocs/framework/react/plugins/broadcastQueryClient.md,.changeset/fix-broadcast-client-unhandled-rejection.mdEstimated code review effort: 3 (Moderate) | ~20 minutes
Merge Risk: ⚪ Minimal · up to
3e362The change contains broadcast message rejection handling and optional error reporting without introducing a supported merge-blocking risk; no actionable merge-blocking risk remains after normal checks and review.
Sequence Diagram(s)#
Possibly related PRs
broadcastQueryClientpostMessageerror-handling changes.Suggested labels:
documentation🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#10543by catching postMessage failures, reporting query context, preventing unhandled rejections, and testing environment-specific behavior.✨ Finishing Touches
🧪 Generate unit tests (beta)
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