|
5 | 5 | type UseQueryOptions, |
6 | 6 | keepPreviousData, |
7 | 7 | } from '@tanstack/react-query' |
| 8 | +import { useRef } from 'react' |
| 9 | +import isEqual from 'lodash.isequal' |
8 | 10 | import { camelizeKeys, decamelizeKeys } from 'humps' |
9 | 11 | import { sendRequest } from '../utils/send-request' |
10 | 12 | import { stringify } from 'qs' |
@@ -44,13 +46,25 @@ export function usePaginatedRequestQuery<TResult = unknown, TError = unknown>( |
44 | 46 | key: QueryKey, |
45 | 47 | request: Request |
46 | 48 | ): 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 | + |
47 | 60 | return useQuery<TResult, TError>({ |
48 | 61 | queryKey: key, |
49 | 62 | queryFn: handleFetch(request), |
50 | 63 | refetchOnWindowFocus: false, |
51 | 64 | refetchOnMount: false, |
52 | 65 | placeholderData: keepPreviousData, |
53 | | - ...camelizeKeys(request.options), |
| 66 | + ...camelizeKeys(options), |
| 67 | + initialData: initialData as TResult | undefined, |
54 | 68 | }) |
55 | 69 | } |
56 | 70 |
|
|
0 commit comments