diff --git a/packages/toolkit/src/query/core/buildThunks.ts b/packages/toolkit/src/query/core/buildThunks.ts index 9e79c3b6a7..ac14635019 100644 --- a/packages/toolkit/src/query/core/buildThunks.ts +++ b/packages/toolkit/src/query/core/buildThunks.ts @@ -523,7 +523,8 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".` getPendingMeta() { return { startedTimeStamp: Date.now(), [SHOULD_AUTOBATCH]: true } }, - condition(queryThunkArgs, { getState }) { + condition(queryThunkArgs, options) { + const { getState } = options const state = getState() const requestState = @@ -551,6 +552,14 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".` return true } + if ( + isQueryDefinition(endpointDefinition) && + endpointDefinition?.skipCondition && + endpointDefinition?.skipCondition(state) + ) { + return false + } + if ( isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({ diff --git a/packages/toolkit/src/query/endpointDefinitions.ts b/packages/toolkit/src/query/endpointDefinitions.ts index 8f7955468c..96d94886d8 100644 --- a/packages/toolkit/src/query/endpointDefinitions.ts +++ b/packages/toolkit/src/query/endpointDefinitions.ts @@ -30,6 +30,7 @@ import type { UnwrapPromise, } from './tsHelpers' import { isNotNullish } from './utils' +import type { QueryThunkArg, ThunkApiMetaConfig } from './core/buildThunks' const resultType = /* @__PURE__ */ Symbol() const baseQuery = /* @__PURE__ */ Symbol() @@ -349,6 +350,8 @@ export interface QueryExtraOptions< */ invalidatesTags?: never + skipCondition?: (state: RootState) => boolean + /** * Can be provided to return a custom cache key value based on the query arguments. * diff --git a/packages/toolkit/src/query/react/buildHooks.ts b/packages/toolkit/src/query/react/buildHooks.ts index 63aadd94e1..fe7d4e7a89 100644 --- a/packages/toolkit/src/query/react/buildHooks.ts +++ b/packages/toolkit/src/query/react/buildHooks.ts @@ -51,6 +51,7 @@ import { UNINITIALIZED_VALUE } from './constants' import type { ReactHooksModuleOptions } from './module' import { useStableQueryArgs } from './useSerializedStableValue' import { useShallowStableValue } from './useShallowStableValue' +import { isQueryDefinition } from '../endpointDefinitions' // Copy-pasted from React-Redux const canUseDOM = () => @@ -1316,9 +1317,17 @@ export function buildHooks({ }, useQuery(arg, options) { const querySubscriptionResults = useQuerySubscription(arg, options) + const store = useStore>() + + const endpointDefinition = context.endpointDefinitions[name] + const shouldSkipFromCondition = + isQueryDefinition(endpointDefinition) && + endpointDefinition?.skipCondition && + endpointDefinition?.skipCondition(store.getState()) + const queryStateResults = useQueryState(arg, { selectFromResult: - arg === skipToken || options?.skip + arg === skipToken || options?.skip || shouldSkipFromCondition ? undefined : noPendingQueryStateSelector, ...options,