Skip to content

Commit d632dd5

Browse files
committed
use getOrInsert in RTKQ
1 parent 3bb8486 commit d632dd5

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

packages/toolkit/src/query/core/buildInitiate.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import type {
1616
QueryDefinition,
1717
ResultTypeFrom,
1818
} from '../endpointDefinitions'
19-
import { countObjectKeys, isNotNullish } from '../utils'
19+
import { countObjectKeys, getOrInsert, isNotNullish } from '../utils'
2020
import type { SubscriptionOptions } from './apiState'
2121
import type { QueryResultSelectorResult } from './buildSelectors'
2222
import type { MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks'
@@ -391,9 +391,8 @@ You must add the middleware for RTK-Query to function correctly!`,
391391
)
392392

393393
if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
394-
const running = runningQueries.get(dispatch) || {}
394+
const running = getOrInsert(runningQueries, dispatch, {})
395395
running[queryCacheKey] = statePromise
396-
runningQueries.set(dispatch, running)
397396

398397
statePromise.then(() => {
399398
delete running[queryCacheKey]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export function getOrInsert<K extends object, V>(
2+
map: WeakMap<K, V>,
3+
key: K,
4+
value: V,
5+
): V
6+
export function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V
7+
export function getOrInsert<K extends object, V>(
8+
map: Map<K, V> | WeakMap<K, V>,
9+
key: K,
10+
value: V,
11+
): V {
12+
if (map.has(key)) return map.get(key) as V
13+
14+
return map.set(key, value).get(key) as V
15+
}

packages/toolkit/src/query/utils/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ export * from './isNotNullish'
88
export * from './isOnline'
99
export * from './isValidUrl'
1010
export * from './joinUrls'
11+
export * from './getOrInsert'

0 commit comments

Comments
 (0)