Skip to content
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

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

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
38 changes: 33 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,17 @@ 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 hasSubscribe = (options: any): options is { subscribe: boolean } =>
'subscribe' in options
const handlePrefetchSubscription = (
result: QueryActionCreatorResult<any>,
subscribe: boolean
): void | QueryActionCreatorResult<any> => {
if (subscribe) {
return result
}
result.unwrap().finally(result.unsubscribe)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this catch and swallow the error?

Copy link
Contributor Author

@bever1337 bever1337 Jan 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opted to unwrap because that seems closer aligned to the lifecycle the end-user is expecting. My hope is it also sidesteps worrying about keepUnusedDataFor being set to 1 second or other cache races I can't think of.

}

const prefetch =
<EndpointName extends QueryKeys<Definitions>>(
Expand All @@ -440,6 +454,8 @@ 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 handleUnsubscribeDownstream =
hasSubscribe(options) && options.subscribe

const queryAction = (force: boolean = true) =>
(api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(
Expand All @@ -451,22 +467,34 @@ In the case of an unhandled error, no tags will be "provided" or "invalidated".`
).select(arg)(getState())

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

Expand Down
7 changes: 6 additions & 1 deletion packages/toolkit/src/query/core/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,21 @@ import { enablePatches } from 'immer'
/**
* `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
* - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
* `subscribe` - (default: `false` | `boolean`)
* - If `true`, `prefetch` will return an interface with `unsubscribe`
*
* @overloadSummary
* `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 }
) & {
subscribe?: boolean
}

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