Skip to content

Commit

Permalink
Fix #2548: pass origin key to subcription callback
Browse files Browse the repository at this point in the history
  • Loading branch information
Zheaoli committed Apr 7, 2023
1 parent bad51f6 commit afe4223
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
3 changes: 2 additions & 1 deletion subscription/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const subscription = (<Data = any, Error = any>(useSWRNext: SWRHook) =>
config: SWRConfiguration & typeof SWRConfig.defaultValue
): SWRSubscriptionResponse<Data, Error> => {
const [key] = serialize(_key)
const originKey = _key

// Prefix the key to avoid conflicts with other SWR resources.
const subscriptionKey = key ? SUBSCRIPTION_PREFIX + key : undefined
Expand Down Expand Up @@ -64,7 +65,7 @@ export const subscription = (<Data = any, Error = any>(useSWRNext: SWRHook) =>
subscriptions.set(subscriptionKey, refCount + 1)

if (!refCount) {
const dispose = subscribe(key, { next })
const dispose = subscribe(originKey, { next })
if (typeof dispose !== 'function') {
throw new Error(
'The `subscribe` function must return a function to unsubscribe.'
Expand Down
56 changes: 56 additions & 0 deletions test/use-swr-subscription.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,62 @@ describe('useSWRSubscription', () => {
screen.getByText(`error:`)
})

it('should pass the origin keys', async () => {
const swrKey = createKey()
let intervalId
let res = 0
function subscribe(key, { next }) {
intervalId = setInterval(() => {
if (res === 3) {
const err = new Error(key)
next(err)
} else {
next(undefined, key[0] + res)
}
res++
}, 100)

return () => {}
}

function Page() {
const { data, error } = useSWRSubscription([swrKey], subscribe, {
fallbackData: 'fallback'
})
return (
<>
<div data-testid="data">{'data:' + data}</div>
<div data-testid="error">
{'error:' + (error ? error.message : '')}
</div>
</>
)
}
renderWithConfig(<Page />)
await act(() => sleep(10))
screen.getByText(`data:fallback`)
screen.getByText('error:')
await act(() => sleep(100))
screen.getByText(`data:${swrKey}0`)
screen.getByText('error:')
await act(() => sleep(100))
screen.getByText(`data:${swrKey}1`)
screen.getByText('error:')
await act(() => sleep(100))
screen.getByText(`data:${swrKey}2`)
screen.getByText('error:')
await act(() => sleep(100))
// error occurred, error arrives instead of data 3
screen.getByText(`data:${swrKey}2`)
screen.getByText(`error:${swrKey}`)
await act(() => sleep(100))
screen.getByText(`data:${swrKey}4`)
screen.getByText('error:')
clearInterval(intervalId)
await sleep(100)
screen.getByText(`error:`)
})

it('should deduplicate subscriptions', async () => {
const swrKey = createKey()

Expand Down

0 comments on commit afe4223

Please sign in to comment.