Skip to content

refactor: optimize render path and improve type safety #984

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

Merged
Merged
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
49 changes: 29 additions & 20 deletions src/core/config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { stableStringify } from './utils'
import {
import type {
ArrayQueryKey,
MutationConfig,
QueryConfig,
QueryKey,
QueryKeySerializerFunction,
ReactQueryConfig,
QueryConfig,
MutationConfig,
ResolvedQueryConfig,
} from './types'
import type { QueryCache } from './queryCache'

// TYPES

Expand Down Expand Up @@ -47,20 +49,19 @@ export const defaultQueryKeySerializerFn: QueryKeySerializerFunction = (
* 2. Defaults from the query cache.
* 3. Query/mutation config provided to the query cache method.
*/
export const DEFAULT_STALE_TIME = 0
export const DEFAULT_CACHE_TIME = 5 * 60 * 1000
export const DEFAULT_CONFIG: ReactQueryConfig = {
queries: {
cacheTime: DEFAULT_CACHE_TIME,
cacheTime: 5 * 60 * 1000,
enabled: true,
notifyOnStatusChange: true,
queryFn: () => Promise.reject(),
queryKeySerializerFn: defaultQueryKeySerializerFn,
refetchOnMount: true,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
retry: 3,
retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
staleTime: DEFAULT_STALE_TIME,
staleTime: 0,
structuralSharing: true,
},
}
Expand All @@ -85,35 +86,44 @@ export function mergeReactQueryConfigs(
}
}

export function getDefaultedQueryConfig<TResult, TError>(
queryCacheConfig?: ReactQueryConfig,
export function getResolvedQueryConfig<TResult, TError>(
queryCache: QueryCache,
queryKey: QueryKey,
contextConfig?: ReactQueryConfig,
config?: QueryConfig<TResult, TError>,
configOverrides?: QueryConfig<TResult, TError>
): QueryConfig<TResult, TError> {
return {
config?: QueryConfig<TResult, TError>
): ResolvedQueryConfig<TResult, TError> {
const queryCacheConfig = queryCache.getDefaultConfig()

const resolvedConfig = {
...DEFAULT_CONFIG.shared,
...DEFAULT_CONFIG.queries,
...queryCacheConfig?.shared,
...queryCacheConfig?.queries,
...contextConfig?.shared,
...contextConfig?.queries,
...config,
...configOverrides,
} as QueryConfig<TResult, TError>
} as ResolvedQueryConfig<TResult, TError>

const result = resolvedConfig.queryKeySerializerFn(queryKey)

resolvedConfig.queryCache = queryCache
resolvedConfig.queryHash = result[0]
resolvedConfig.queryKey = result[1]

return resolvedConfig
}

export function getDefaultedMutationConfig<
export function getResolvedMutationConfig<
TResult,
TError,
TVariables,
TSnapshot
>(
queryCacheConfig?: ReactQueryConfig,
queryCache: QueryCache,
contextConfig?: ReactQueryConfig,
config?: MutationConfig<TResult, TError, TVariables, TSnapshot>,
configOverrides?: MutationConfig<TResult, TError, TVariables, TSnapshot>
config?: MutationConfig<TResult, TError, TVariables, TSnapshot>
): MutationConfig<TResult, TError, TVariables, TSnapshot> {
const queryCacheConfig = queryCache.getDefaultConfig()
return {
...DEFAULT_CONFIG.shared,
...DEFAULT_CONFIG.mutations,
Expand All @@ -122,6 +132,5 @@ export function getDefaultedMutationConfig<
...contextConfig?.shared,
...contextConfig?.mutations,
...config,
...configOverrides,
} as MutationConfig<TResult, TError, TVariables, TSnapshot>
}
58 changes: 21 additions & 37 deletions src/core/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,16 @@ import {
isOnline,
isServer,
isValidTimeout,
noop,
replaceEqualDeep,
sleep,
} from './utils'
import {
ArrayQueryKey,
InitialDataFunction,
IsFetchingMoreValue,
QueryConfig,
QueryFunction,
QueryStatus,
ResolvedQueryConfig,
} from './types'
import type { QueryCache } from './queryCache'
import { QueryObserver, UpdateListener } from './queryObserver'
Expand Down Expand Up @@ -101,7 +100,7 @@ export type Action<TResult, TError> =
export class Query<TResult, TError> {
queryKey: ArrayQueryKey
queryHash: string
config: QueryConfig<TResult, TError>
config: ResolvedQueryConfig<TResult, TError>
observers: QueryObserver<TResult, TError>[]
state: QueryState<TResult, TError>
cacheTime: number
Expand All @@ -113,24 +112,20 @@ export class Query<TResult, TError> {
private continueFetch?: () => void
private isTransportCancelable?: boolean

constructor(
queryKey: ArrayQueryKey,
queryHash: string,
config: QueryConfig<TResult, TError>
) {
constructor(config: ResolvedQueryConfig<TResult, TError>) {
this.config = config
this.queryKey = queryKey
this.queryHash = queryHash
this.queryCache = config.queryCache!
this.queryKey = config.queryKey
this.queryHash = config.queryHash
this.queryCache = config.queryCache
this.cacheTime = config.cacheTime
this.observers = []
this.state = getDefaultState(config)
this.cacheTime = config.cacheTime!
this.scheduleGc()
}

private updateConfig(config: QueryConfig<TResult, TError>): void {
private updateConfig(config: ResolvedQueryConfig<TResult, TError>): void {
this.config = config
this.cacheTime = Math.max(this.cacheTime, config.cacheTime || 0)
this.cacheTime = Math.max(this.cacheTime, config.cacheTime)
}

private dispatch(action: Action<TResult, TError>): void {
Expand Down Expand Up @@ -247,7 +242,7 @@ export class Query<TResult, TError> {
)

if (staleObserver) {
staleObserver.fetch().catch(noop)
staleObserver.fetch()
}

// Continue any paused fetch
Expand All @@ -257,14 +252,8 @@ export class Query<TResult, TError> {
subscribe(
listener?: UpdateListener<TResult, TError>
): QueryObserver<TResult, TError> {
const observer = new QueryObserver<TResult, TError>({
queryCache: this.queryCache,
queryKey: this.queryKey,
...this.config,
})

const observer = new QueryObserver(this.config)
observer.subscribe(listener)

return observer
}

Expand All @@ -291,7 +280,7 @@ export class Query<TResult, TError> {

async refetch(
options?: RefetchOptions,
config?: QueryConfig<TResult, TError>
config?: ResolvedQueryConfig<TResult, TError>
): Promise<TResult | undefined> {
try {
return await this.fetch(undefined, config)
Expand All @@ -305,7 +294,7 @@ export class Query<TResult, TError> {
async fetchMore(
fetchMoreVariable?: unknown,
options?: FetchMoreOptions,
config?: QueryConfig<TResult, TError>
config?: ResolvedQueryConfig<TResult, TError>
): Promise<TResult | undefined> {
return this.fetch(
{
Expand All @@ -320,7 +309,7 @@ export class Query<TResult, TError> {

async fetch(
options?: FetchOptions,
config?: QueryConfig<TResult, TError>
config?: ResolvedQueryConfig<TResult, TError>
): Promise<TResult | undefined> {
// If we are already fetching, return current promise
if (this.promise) {
Expand All @@ -334,11 +323,6 @@ export class Query<TResult, TError> {

config = this.config

// Check if there is a query function
if (typeof config.queryFn !== 'function') {
return
}

// Get the query function params
const filter = config.queryFnParamsFilter
const params = filter ? filter(this.queryKey) : this.queryKey
Expand Down Expand Up @@ -385,12 +369,12 @@ export class Query<TResult, TError> {
}

private async startFetch(
config: QueryConfig<TResult, TError>,
config: ResolvedQueryConfig<TResult, TError>,
params: unknown[],
_options?: FetchOptions
): Promise<TResult> {
// Create function to fetch the data
const fetchData = () => config.queryFn!(...params)
const fetchData = () => config.queryFn(...params)

// Set to fetching state if not already in it
if (!this.state.isFetching) {
Expand All @@ -402,7 +386,7 @@ export class Query<TResult, TError> {
}

private async startInfiniteFetch(
config: QueryConfig<TResult, TError>,
config: ResolvedQueryConfig<TResult, TError>,
params: unknown[],
options?: FetchOptions
): Promise<TResult[]> {
Expand All @@ -427,7 +411,7 @@ export class Query<TResult, TError> {
cursor = config.getFetchMore(lastPage, pages)
}

const page = await config.queryFn!(...params, cursor)
const page = await config.queryFn(...params, cursor)

return prepend ? [page, ...pages] : [...pages, page]
}
Expand Down Expand Up @@ -457,7 +441,7 @@ export class Query<TResult, TError> {
}

private async tryFetchData<T>(
config: QueryConfig<TResult, TError>,
config: ResolvedQueryConfig<TResult, TError>,
fn: QueryFunction<T>
): Promise<T> {
return new Promise<T>((outerResolve, outerReject) => {
Expand Down Expand Up @@ -567,7 +551,7 @@ function getLastPage<TResult>(pages: TResult[], previous?: boolean): TResult {
}

function hasMorePages<TResult, TError>(
config: QueryConfig<TResult, TError>,
config: ResolvedQueryConfig<TResult, TError>,
pages: unknown,
previous?: boolean
): boolean | undefined {
Expand All @@ -577,7 +561,7 @@ function hasMorePages<TResult, TError>(
}

function getDefaultState<TResult, TError>(
config: QueryConfig<TResult, TError>
config: ResolvedQueryConfig<TResult, TError>
): QueryState<TResult, TError> {
const initialData =
typeof config.initialData === 'function'
Expand Down
Loading