.jsonp.
tRPC17mo ago
1 reply
.jsonp

How to get pageParam from useInfiniteQuery()?

How would I write a tRPC call equivalent to this traditional useInfiniteQuery? My primary concern here is that I need to pass in a cursor to my procedure, and upon each successive query I need to update this cursor for the next call.

  const {
    data: posts,
    isFetching,
    error,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery({
    queryKey: ["profile-posts", username],
    queryFn: ({ pageParam }) =>
      kyInstance
        .get(
          `/api/profiles/${username}/posts`,
          pageParam ? { searchParams: { cursor: pageParam } } : {},
        )
        .json<TProfilePostsPage>(),
    initialPageParam: null as string | null,
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  });


Maybe it should be something like this?

  const [nextCursor, setNextCursor] = useState<string | null>(null)

  const {
    data: posts,
    isFetching,
    error,
    hasNextPage,
    fetchNextPage,
  } = trpc.getProfilePosts.useInfiniteQuery({ username, cursor: nextCursor }, {
    queryKey: ["profile-posts", username],
    initialPageParam: null as string | null,
    getNextPageParam: (lastPage) => {
      setNextCursor(lastPage.nextCursor)
      return lastPage.nextCursor
    },
  });
Was this page helpful?