Skip to content

feat(query): Adds subscribe option to prefetch, automatically unsubscribes if not present [#1283] #1938

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions packages/toolkit/src/query/core/buildThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import type {
import { BaseQueryArg } from '../baseQueryTypes'
import type { RootState, QueryKeys, QuerySubstateIdentifier } from './apiState'
import { QueryStatus, CombinedState } from './apiState'
import type { StartQueryActionCreatorOptions } from './buildInitiate'
import type {
QueryActionCreatorResult,
StartQueryActionCreatorOptions,
} from './buildInitiate'
import type {
AssertTagTypes,
EndpointDefinition,
Expand Down Expand Up @@ -430,6 +433,8 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".`
const hasMaxAge = (
options: any
): options is { ifOlderThan: false | number } => 'ifOlderThan' in options
const hasCleanup = (options: any): options is { cleanup?: boolean } =>
'cleanup' in options

const prefetch =
<EndpointName extends QueryKeys<Definitions>>(
Expand All @@ -440,33 +445,42 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".`
(dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {
const force = hasTheForce(options) && options.force
const maxAge = hasMaxAge(options) && options.ifOlderThan
const cleanupSubscription = hasCleanup(options) && options.cleanup

const queryAction = (force: boolean = true) =>
(api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(
arg,
{ forceRefetch: force }
)
const queryCleanup = (
result: QueryActionCreatorResult<any>,
doCleanup: boolean = false
) => {
if (doCleanup) {
result.unwrap().finally(result.unsubscribe)
}
}
const latestStateValue = (
api.endpoints[endpointName] as ApiEndpointQuery<any, any>
).select(arg)(getState())

if (force) {
dispatch(queryAction())
queryCleanup(dispatch(queryAction()), cleanupSubscription)
} else if (maxAge) {
const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp
if (!lastFulfilledTs) {
dispatch(queryAction())
queryCleanup(dispatch(queryAction()), cleanupSubscription)
return
}
const shouldRetrigger =
(Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >=
maxAge
if (shouldRetrigger) {
dispatch(queryAction())
queryCleanup(dispatch(queryAction()), cleanupSubscription)
}
} else {
// If prefetching with no options, just let it try
dispatch(queryAction(false))
queryCleanup(dispatch(queryAction(false)), cleanupSubscription)
}
}

Expand Down
5 changes: 4 additions & 1 deletion packages/toolkit/src/query/core/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ import { enablePatches } from 'immer'
* `force`
* - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
*/
export type PrefetchOptions =
export type PrefetchOptions = (
| {
ifOlderThan?: false | number
}
| { force?: boolean }
) & {
cleanup?: boolean
}

export const coreModuleName = /* @__PURE__ */ Symbol()
export type CoreModule =
Expand Down