Skip to content

fix: write subscription updates to the subscribed key - #4341

Open
kwy404 wants to merge 1 commit into
vercel:mainfrom
kwy404:fix/subscription-key-change
Open

kwy404 wants to merge 1 commit into
vercel:mainfrom
kwy404:fix/subscription-key-change

Conversation

@kwy404

@kwy404 kwy404 commented Sep 26, 2026

Copy link
Copy Markdown

When several useSWRSubscription hooks share a key, the subscription is created once by the hook that mounts first, and its next callback writes data through that hook's swr.mutate. That bound mutate always targets the hook's current key (keyRef.current), not the key the subscription was created for. So if the first hook switches to another key while another hook keeps the shared subscription alive, every update for the old key is written into the cache of the new key. The hook that stayed on the old key stops updating, and the hook that moved shows data from the wrong source. Errors are not affected because next already writes them with a cache helper bound to subscriptionKey.

The fix writes data with internalMutate(cache, subscriptionKey, data, false), the same key the error path uses.

Test: should keep updating a shared key after one hook switches keys in test/use-swr-subscription.test.tsx. One component has two hooks on keyA, switches the first one to keyB, then emits on keyA. Before the fix it renders a2:a1 (the keyB hook got the keyA data and the keyA hook is stale) and the test fails. After the fix it renders undefined:a2 and the test passes. The other subscription tests, tsc, oxlint and oxfmt pass.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant