0

I'm converting some code to use TanStack ReactQuery useInfiniteQuery hook.

Everything is working, EXCEPT when loading new data, instead of the next page's results the 1st page's data gets duplicated.

Calling the fetchNextPage method triggers a re-render but returns the 1st page's cached data instead of fetching new data. i.e. my gqlListOrdersByAccountIdAndDate() function is only called once. The getNextPageParam function is correctly returning the next token.

I thought perhaps I need to add the value from pageParam/nextToken to the queryKey so it'll be unique, but absolutely none of the examples I've seen do that. Not sure why I keep getting the cached data instead of fetching the next page.

Here's the component:

import { useInfiniteQuery } from "@tanstack/react-query"
import { gqlListOrdersByAccountIdAndDate } from "../utils/gqlListOrdersByAccountIdAndDate"

const Orders = ({ accountId }: { accountId: string }) => {

  const listOrders = async ({ pageParam = null }) =>
    gqlListOrdersByAccountIdAndDate(accountId, pageParam)

  const { error, isLoading, fetchNextPage, data } = useInfiniteQuery({
    queryKey: ['orders', accountId],
    queryFn: listOrders,
    getNextPageParam: (lastPage, pages) => lastPage.data?.ordersByAccountIdAndDate?.nextToken
  })

  const orders = data?.pages.flatMap(p => p.data?.ordersByAccountIdAndDate?.items)

  return <InfiniteTable items={orders} fetchMore={fetchNextPage} />
}

export default Orders

The query is just GQL, but I've artificially limited it to only return 5 results for testing.

export async function gqlListOrdersByAccountIdAndDate(accountOrdersId: string, nextPage: string | null) {
  console.log('gqlListOrdersByAccountIdAndDate', accountOrdersId, nextPage)
  return API.graphql<GraphQLQuery<OrdersByAccountIdAndDateQuery>>(
    graphqlOperation(
      ordersByAccountIdAndDate,
      { accountOrdersId, nextToken: null, sortDirection: 'DESC', limit: 5 })
  )
}
Dave
  • 7,552
  • 4
  • 22
  • 26

0 Answers0