1

I want to implement an infinite scroll in a component, but my back-end doesn't have a "current" endpoint which means that the actual version of infiniteQuery is out of the question (as far as I understand).

In my component I created a query using a stateful variable as a queryKey parameter:

useQuery([`posts_paginated`, { page }] {
    // request to  http://.../posts?_sort=createdAt&_order=desc&_page=${page}&_limit=10
}

My issue is that modifying the query key creates a new query instance triggering the isLoading boolean in the response object and the rendering value of the component depends an that:

return (IsLoading) ? <LoadingComponent /> : <ViewComponent />

This means that when the page variable is set, the ViewComponent is unmounted with the result that I lose the current position of the scrolling bar.

I tried invalidating the query instead so that only isFetching would trigger, but I think that since the callback closure for the query is already set the parameters values can't be changed that way (I couldn't get it to run with anything but the initial values).

I could stop rendering contitionally with isLoading or I could start managing my scroll bar position explicitely in some state, but I'm wondering if there is an obvious way to achieve what I need just using react-query.

1 Answer 1

1

pagination like this can be achieved by setting the keepPreviousData prop. it will keep the data of the previous query key returned as data when the key changes, along with a isPreviousData boolean flag so that you can maybe disable the next button or show a background loading indicator depending on it. The query will then always stay in success state, and the data will then transition directly to the new data when it arrives.

This is also described in the pagination docs

Also, I think you can get a "real" infinite query working even if the backend is paginated. getNextPageParam just needs something returned from the function that can then be "injected" into the queryFn. If you just want to return a count of the current pages in the cache and increment that by one each time - I don't think there is anything bad about this :)

Sign up to request clarification or add additional context in comments.

1 Comment

using my code and plugging in keepPreviousData on true just worked immedietely. I wasn't able to make infiniteQuery work. I suspect having hashed ids for my documents isn't compatible with cursor logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.