1

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

3
  • Is caching not enabled on the API? Commented Nov 3, 2022 at 16:15
  • @inf3rno no unfortunately, I do not have control over this API either. Caching individual responses is important because the response times for each individual api call is quite slow :/ Commented Nov 4, 2022 at 2:07
  • Isn't it possible to add some sort of caching HTTP proxy to your system? I would rather go to that direction if possible. Commented Nov 4, 2022 at 11:35

1 Answer 1

2

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.

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

Comments

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.