Skip to content

Commit f41db88

Browse files
committed
Cleanup polls on unsubscribeQueryResult
1 parent 637b0ca commit f41db88

File tree

1 file changed

+23
-7
lines changed
  • packages/toolkit/src/query/core/buildMiddleware

1 file changed

+23
-7
lines changed

packages/toolkit/src/query/core/buildMiddleware/polling.ts

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,30 @@ export const build: SubMiddlewareBuilder = ({
1919
timeout?: TimeoutId
2020
pollingInterval: number
2121
}> = {}
22+
23+
function cleanupPollForKey(key: string) {
24+
const existingPoll = currentPolls[key]
25+
existingPoll?.timeout && clearTimeout(existingPoll.timeout)
26+
delete currentPolls[key]
27+
}
28+
2229
return (next) =>
2330
(action): any => {
2431
const result = next(action)
2532

33+
if (api.internalActions.unsubscribeQueryResult.match(action)) {
34+
const { queryCacheKey } = action.payload
35+
const existingSubscriptionCount = Object.keys(
36+
mwApi.getState()[reducerPath].subscriptions[queryCacheKey] || {}
37+
).length
38+
39+
// There are no other components subscribed and sharing a poll for this queryCacheKey, so we can
40+
// safely remove it
41+
if (existingSubscriptionCount === 0) {
42+
cleanupPollForKey(queryCacheKey)
43+
}
44+
}
45+
2646
if (api.internalActions.updateSubscriptionOptions.match(action)) {
2747
updatePollingInterval(action.payload, mwApi)
2848
}
@@ -102,10 +122,7 @@ export const build: SubMiddlewareBuilder = ({
102122
const currentPoll = currentPolls[queryCacheKey]
103123

104124
if (!Number.isFinite(lowestPollingInterval)) {
105-
if (currentPoll?.timeout) {
106-
clearTimeout(currentPoll.timeout)
107-
}
108-
delete currentPolls[queryCacheKey]
125+
cleanupPollForKey(queryCacheKey)
109126
return
110127
}
111128

@@ -117,9 +134,8 @@ export const build: SubMiddlewareBuilder = ({
117134
}
118135

119136
function clearPolls() {
120-
for (const [key, poll] of Object.entries(currentPolls)) {
121-
if (poll?.timeout) clearTimeout(poll.timeout)
122-
delete currentPolls[key]
137+
for (const key of Object.keys(currentPolls)) {
138+
cleanupPollForKey(key)
123139
}
124140
}
125141
}

0 commit comments

Comments
 (0)