Skip to content

Commit 0a32a5c

Browse files
committed
Only pass initialPageParams option through query hook
1 parent f9df3b0 commit 0a32a5c

File tree

2 files changed

+124
-71
lines changed

2 files changed

+124
-71
lines changed

packages/toolkit/src/query/react/buildHooks.ts

Lines changed: 18 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -790,7 +790,9 @@ export type LazyInfiniteQueryTrigger<
790790
): InfiniteQueryActionCreatorResult<D>
791791
}
792792

793-
interface UseInfiniteQuerySubscriptionOptions extends SubscriptionOptions {
793+
interface UseInfiniteQuerySubscriptionOptions<
794+
D extends InfiniteQueryDefinition<any, any, any, any, any>,
795+
> extends SubscriptionOptions {
794796
/**
795797
* Prevents a query from automatically running.
796798
*
@@ -833,6 +835,7 @@ interface UseInfiniteQuerySubscriptionOptions extends SubscriptionOptions {
833835
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
834836
*/
835837
refetchOnMountOrArgChange?: boolean | number
838+
initialPageParam?: PageParamFrom<D>
836839
}
837840

838841
export type TypedUseInfiniteQuerySubscription<
@@ -884,19 +887,14 @@ export type UseInfiniteQuery<
884887
D extends InfiniteQueryDefinition<any, any, any, any, any>,
885888
> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
886889
arg: InfiniteQueryArgFrom<D> | SkipToken,
887-
options?: UseInfiniteQuerySubscriptionOptions &
888-
UseInfiniteQueryStateOptions<D, R> &
889-
InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>>,
890+
options?: UseInfiniteQuerySubscriptionOptions<D> &
891+
UseInfiniteQueryStateOptions<D, R>,
890892
) => UseInfiniteQueryHookResult<D, R>
891893

892894
export type UseInfiniteQueryState<
893895
D extends InfiniteQueryDefinition<any, any, any, any, any>,
894896
> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
895897
arg: QueryArgFrom<D> | SkipToken,
896-
InfiniteQueryConfigOptions: InfiniteQueryConfigOptions<
897-
ResultTypeFrom<D>,
898-
PageParamFrom<D>
899-
>,
900898
options?: UseInfiniteQueryStateOptions<D, R>,
901899
) => UseInfiniteQueryStateResult<D, R>
902900

@@ -920,7 +918,7 @@ export type UseInfiniteQuerySubscription<
920918
D extends InfiniteQueryDefinition<any, any, any, any, any>,
921919
> = (
922920
arg: QueryArgFrom<D> | SkipToken,
923-
options?: UseInfiniteQuerySubscriptionOptions,
921+
options?: UseInfiniteQuerySubscriptionOptions<D>,
924922
) => readonly [
925923
LazyInfiniteQueryTrigger<D>,
926924
QueryArgFrom<D> | UninitializedValue,
@@ -1758,6 +1756,7 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
17581756
skip = false,
17591757
pollingInterval = 0,
17601758
skipPollingIfUnfocused = false,
1759+
initialPageParam,
17611760
} = {},
17621761
) => {
17631762
const { initiate } = api.endpoints[
@@ -1858,6 +1857,7 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
18581857
lastPromise?.unsubscribe()
18591858
const promise = dispatch(
18601859
initiate(stableArg, {
1860+
initialPageParam,
18611861
subscriptionOptions: stableSubscriptionOptions,
18621862
forceRefetch: refetchOnMountOrArgChange,
18631863
}),
@@ -1874,6 +1874,7 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
18741874
stableArg,
18751875
stableSubscriptionOptions,
18761876
subscriptionRemoved,
1877+
initialPageParam,
18771878
])
18781879

18791880
const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
@@ -1913,7 +1914,6 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
19131914

19141915
const useInfiniteQueryState: UseInfiniteQueryState<any> = (
19151916
arg: any,
1916-
{ getNextPageParam, getPreviousPageParam },
19171917
{ skip = false, selectFromResult, trigger } = {},
19181918
) => {
19191919
const { select, initiate } = api.endpoints[
@@ -1984,22 +1984,14 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
19841984
useInfiniteQuerySubscription,
19851985
useInfiniteQuery(arg, options) {
19861986
const [trigger] = useInfiniteQuerySubscription(arg, options)
1987-
const queryStateResults = useInfiniteQueryState(
1988-
arg,
1989-
{
1990-
initialPageParam: options?.initialPageParam!,
1991-
getNextPageParam: options?.getNextPageParam!,
1992-
getPreviousPageParam: options?.getPreviousPageParam,
1993-
},
1994-
{
1995-
selectFromResult:
1996-
arg === skipToken || options?.skip
1997-
? undefined
1998-
: noPendingQueryStateSelector,
1999-
trigger,
2000-
...options,
2001-
},
2002-
)
1987+
const queryStateResults = useInfiniteQueryState(arg, {
1988+
selectFromResult:
1989+
arg === skipToken || options?.skip
1990+
? undefined
1991+
: noPendingQueryStateSelector,
1992+
trigger,
1993+
...options,
1994+
})
20031995

20041996
const {
20051997
data,

packages/toolkit/src/query/tests/buildHooks.test.tsx

Lines changed: 106 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@ afterEach(() => {
181181
nextItemId = 0
182182
amount = 0
183183
listenerMiddleware.clearListeners()
184+
185+
server.resetHandlers()
184186
})
185187

186188
let getRenderCount: () => number = () => 0
@@ -1693,6 +1695,14 @@ describe('hooks tests', () => {
16931695
lastPageParam,
16941696
allPageParams,
16951697
) => lastPageParam + 1,
1698+
getPreviousPageParam: (
1699+
firstPage,
1700+
allPages,
1701+
firstPageParam,
1702+
allPageParams,
1703+
) => {
1704+
return firstPageParam > 0 ? firstPageParam - 1 : undefined
1705+
},
16961706
},
16971707
query(pageParam) {
16981708
return `https://example.com/listItems?page=${pageParam}`
@@ -1702,57 +1712,66 @@ describe('hooks tests', () => {
17021712
})
17031713

17041714
function PokemonList({
1715+
arg = 'fire',
17051716
initialPageParam = 0,
17061717
}: {
1718+
arg?: string
17071719
initialPageParam?: number
17081720
}) {
1709-
const { data, isFetching, isUninitialized, fetchNextPage } =
1710-
pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery('a', {
1711-
initialPageParam,
1712-
getNextPageParam: (
1713-
lastPage,
1714-
allPages,
1715-
// Page param type should be `number`
1716-
lastPageParam,
1717-
allPageParams,
1718-
) => lastPageParam + 1,
1719-
})
1721+
const {
1722+
data,
1723+
isFetching,
1724+
isUninitialized,
1725+
fetchNextPage,
1726+
fetchPreviousPage,
1727+
} = pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery(arg, {
1728+
initialPageParam,
1729+
})
1730+
1731+
const handlePreviousPage = async () => {
1732+
const res = await fetchPreviousPage()
1733+
}
17201734

1721-
const handleClick = async () => {
1722-
const promise = fetchNextPage()
1723-
const res = await promise
1735+
const handleNextPage = async () => {
1736+
const res = await fetchNextPage()
17241737
}
17251738

17261739
return (
17271740
<div>
17281741
<div data-testid="isUninitialized">{String(isUninitialized)}</div>
17291742
<div data-testid="isFetching">{String(isFetching)}</div>
1743+
<div>Type: {arg}</div>
17301744
<div data-testid="data">
1731-
{data?.pages.map((page: any, i: number | null | undefined) => (
1732-
<div key={i}>{JSON.stringify(page)}</div>
1745+
{data?.pages.map((page, i: number | null | undefined) => (
1746+
<div key={i}>{page.name}</div>
17331747
))}
17341748
</div>
1735-
<button data-testid="nextPage" onClick={() => handleClick()}>
1749+
<button data-testid="prevPage" onClick={() => handlePreviousPage()}>
1750+
nextPage
1751+
</button>
1752+
<button data-testid="nextPage" onClick={() => handleNextPage()}>
17361753
nextPage
17371754
</button>
17381755
</div>
17391756
)
17401757
}
17411758

1742-
server.use(
1743-
http.get('https://example.com/listItems', ({ request }) => {
1744-
const url = new URL(request.url)
1745-
const pageString = url.searchParams.get('page')
1746-
const pageNum = parseInt(pageString || '0')
1747-
1748-
const results: Pokemon = {
1749-
id: `${pageNum}`,
1750-
name: `Pokemon ${pageNum}`,
1751-
}
1759+
beforeEach(() => {
1760+
server.use(
1761+
http.get('https://example.com/listItems', ({ request }) => {
1762+
const url = new URL(request.url)
1763+
const pageString = url.searchParams.get('page')
1764+
const pageNum = parseInt(pageString || '0')
1765+
1766+
const results: Pokemon = {
1767+
id: `${pageNum}`,
1768+
name: `Pokemon ${pageNum}`,
1769+
}
17521770

1753-
return HttpResponse.json(results)
1754-
}),
1755-
)
1771+
return HttpResponse.json(results)
1772+
}),
1773+
)
1774+
})
17561775

17571776
test('useInfiniteQuery fetchNextPage Trigger', async () => {
17581777
const storeRef = setupApiStore(pokemonApi, undefined, {
@@ -1762,34 +1781,76 @@ describe('hooks tests', () => {
17621781
const checkNumQueries = (count: number) => {
17631782
const cacheEntries = Object.keys(storeRef.store.getState().api.queries)
17641783
const queries = cacheEntries.length
1765-
console.log('queries', queries, storeRef.store.getState().api.queries)
1784+
//console.log('queries', queries, storeRef.store.getState().api.queries)
17661785

17671786
expect(queries).toBe(count)
17681787
}
17691788

1770-
render(<PokemonList />, { wrapper: storeRef.wrapper })
1789+
const checkPageRows = (type: string, ids: number[]) => {
1790+
expect(screen.getByText(`Type: ${type}`)).toBeTruthy()
1791+
for (const id of ids) {
1792+
expect(screen.getByText(`Pokemon ${id}`)).toBeTruthy()
1793+
}
1794+
}
1795+
1796+
async function waitForFetch() {
1797+
await waitFor(() =>
1798+
expect(screen.getByTestId('isFetching').textContent).toBe('true'),
1799+
)
1800+
await waitFor(() =>
1801+
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
1802+
)
1803+
}
1804+
1805+
const utils = render(<PokemonList />, { wrapper: storeRef.wrapper })
17711806
expect(screen.getByTestId('data').textContent).toBe('')
17721807
checkNumQueries(1)
17731808

17741809
await waitFor(() =>
17751810
expect(screen.getByTestId('isUninitialized').textContent).toBe('false'),
17761811
)
1777-
await waitFor(() =>
1778-
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
1779-
)
1812+
1813+
// Initial load
1814+
await waitForFetch()
1815+
checkNumQueries(1)
1816+
checkPageRows('fire', [0])
1817+
17801818
act(() => {
17811819
fireEvent.click(screen.getByTestId('nextPage'))
17821820
})
1783-
await waitFor(() =>
1784-
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
1785-
)
1786-
checkNumQueries(1)
1787-
await waitFor(() =>
1788-
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
1789-
)
1790-
expect(screen.getByTestId('data').textContent).toBe(
1791-
'{"id":"0","name":"Pokemon 0"}{"id":"1","name":"Pokemon 1"}',
1792-
)
1821+
1822+
await waitForFetch()
1823+
1824+
// Added one page
1825+
checkPageRows('fire', [0, 1])
1826+
1827+
act(() => {
1828+
fireEvent.click(screen.getByTestId('nextPage'))
1829+
})
1830+
await waitForFetch()
1831+
1832+
checkPageRows('fire', [0, 1, 2])
1833+
1834+
utils.rerender(<PokemonList arg="water" initialPageParam={3} />)
1835+
1836+
await waitForFetch()
1837+
1838+
checkNumQueries(2)
1839+
checkPageRows('water', [3])
1840+
1841+
act(() => {
1842+
fireEvent.click(screen.getByTestId('nextPage'))
1843+
})
1844+
await waitForFetch()
1845+
1846+
checkPageRows('water', [3, 4])
1847+
1848+
act(() => {
1849+
fireEvent.click(screen.getByTestId('prevPage'))
1850+
})
1851+
await waitForFetch()
1852+
1853+
checkPageRows('water', [2, 3, 4])
17931854
})
17941855
})
17951856

0 commit comments

Comments
 (0)