Ross Sullivan
Ross Sullivan

Reputation: 435

React Query dynamic incremental queries

I am currently fetching data from a 3rd party api in a React application.

The way the api is structured, the flow goes like this:

// Get a list of data
response = GET /reviews

while response.data.nextPageUrl is not null
   response = GET ${response.data.nextPageUrl}

I currently have this logic inside of a "fetch method"

const fetchMyData = () => {
  // The logic above
}

const query = useQuery(['myKey'], () => fetchMyData, {...}) 

This works, but comes with some drawbacks.

  1. There is no way to see the progress of the individual requests (to be used in a progress bar)

  2. It cannot leverage React Query's caching functionality on an individual request. For example: If there are 10 requests to be made, but during the 5th request the user refreshes the page, they will need to restart from the beginning.

I am aware of useQueries but since I do not know the query urls until I have received the first request I do not see how I could use it.

Is there a better approach or way to satisfy the 2 issues above? Thank you in advance

Upvotes: 1

Views: 2211

Answers (1)

Gerardo Sabetta
Gerardo Sabetta

Reputation: 579

What you need is Infinite Queries. useInfiniteQuery works similar to useQuery but it's made for fetching by chunks. useInfiniteQuery has extra parameters like getNextPageParam which you will use to tell React Query how to determine the next page. This hook also returns fetchNextPage, hasNextPage (among others), which will allow you to implement patterns like a "show more" button that appears for as long as there is a next page.

By using infinite queries you still leverage on React Query caching. Check the docs for more info.

Upvotes: 2

Related Questions