Skip to content

Commit

Permalink
use getOrInsert in RTKQ
Browse files Browse the repository at this point in the history
  • Loading branch information
EskiMojo14 committed Nov 27, 2024
1 parent 3bb8486 commit d632dd5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
5 changes: 2 additions & 3 deletions packages/toolkit/src/query/core/buildInitiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type {
QueryDefinition,
ResultTypeFrom,
} from '../endpointDefinitions'
import { countObjectKeys, isNotNullish } from '../utils'
import { countObjectKeys, getOrInsert, isNotNullish } from '../utils'
import type { SubscriptionOptions } from './apiState'
import type { QueryResultSelectorResult } from './buildSelectors'
import type { MutationThunk, QueryThunk, QueryThunkArg } from './buildThunks'
Expand Down Expand Up @@ -391,9 +391,8 @@ You must add the middleware for RTK-Query to function correctly!`,
)

if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
const running = runningQueries.get(dispatch) || {}
const running = getOrInsert(runningQueries, dispatch, {})
running[queryCacheKey] = statePromise
runningQueries.set(dispatch, running)

statePromise.then(() => {
delete running[queryCacheKey]
Expand Down
15 changes: 15 additions & 0 deletions packages/toolkit/src/query/utils/getOrInsert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function getOrInsert<K extends object, V>(
map: WeakMap<K, V>,
key: K,
value: V,
): V
export function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V
export function getOrInsert<K extends object, V>(
map: Map<K, V> | WeakMap<K, V>,
key: K,
value: V,
): V {
if (map.has(key)) return map.get(key) as V

return map.set(key, value).get(key) as V
}
1 change: 1 addition & 0 deletions packages/toolkit/src/query/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export * from './isNotNullish'
export * from './isOnline'
export * from './isValidUrl'
export * from './joinUrls'
export * from './getOrInsert'

0 comments on commit d632dd5

Please sign in to comment.