Skip to content

Commit 33221a9

Browse files
authored
Prevent flash of stale initialData when query changes (#7977)
* Prevent flash of stale initialData when query changes * Make it more robust
1 parent f93c554 commit 33221a9

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

app/javascript/hooks/request-query.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
type UseQueryOptions,
66
keepPreviousData,
77
} from '@tanstack/react-query'
8+
import { useRef } from 'react'
9+
import isEqual from 'lodash.isequal'
810
import { camelizeKeys, decamelizeKeys } from 'humps'
911
import { sendRequest } from '../utils/send-request'
1012
import { stringify } from 'qs'
@@ -44,13 +46,25 @@ export function usePaginatedRequestQuery<TResult = unknown, TError = unknown>(
4446
key: QueryKey,
4547
request: Request
4648
): UseQueryResult<TResult, TError> {
49+
const { query = {}, options = {} } = request
50+
51+
// we are storing the initial query on mount to detect when it changes.
52+
const initialQueryRef = useRef(query)
53+
// if the query changes (e.g. due to search or pagination), we omit initialData
54+
// so tanstack query doesn't briefly show outdated initial data during the transition,
55+
// and previously fetched data can take over.
56+
// this avoids visual flashes where irrelevant initial data appears before new data loads.
57+
const queryChanged = !isEqual(initialQueryRef.current, query)
58+
const initialData = queryChanged ? undefined : options?.initialData
59+
4760
return useQuery<TResult, TError>({
4861
queryKey: key,
4962
queryFn: handleFetch(request),
5063
refetchOnWindowFocus: false,
5164
refetchOnMount: false,
5265
placeholderData: keepPreviousData,
53-
...camelizeKeys(request.options),
66+
...camelizeKeys(options),
67+
initialData: initialData as TResult | undefined,
5468
})
5569
}
5670

0 commit comments

Comments
 (0)