Question about the best way to paginate and filter an API request
Guys, I believe you can help me 🙂
I am having trouble to understand what's the best way to fetch a request based on: An API which can be paginated and filtered based on some query parameters.
Neither of those are query keys (pagination and query parameters), so I storage my pagination and query parameters in React State. When the user changes some of those, it should trigger the query refetch inside useEffect.
My question is:
- let assume my initial request went well, and it's display the table data.
- Then, I want to match a exact filter. So I change the state, a refetch is triggered, but the API return an error.
- The table keeps display the option to paginate, based on keepPreviousData: true
- So I tried to paginate, but the API returns an error again, because the react state I sent previously is still storage, so it's keeps sending.
Can I have a better way to "undo" pagination state? Which strategies are good to take a look?
1 Reply
firm-tan•3y ago
Neither of those are query keys (pagination and query parameters), so I storage my pagination and query parameters in React State. When the user changes some of those, it should trigger the query refetch inside useEffect.I would strongly advise putting the pagination and filter parameters (and any other query param) in the query key. The query will automatically be refetched when any of those changes and each value will have a seperate cache. That's the recommended way in the docs: https://tanstack.com/query/latest/docs/react/guides/paginated-queries And that would most probably solve your issue
Paginated / Lagged Queries | TanStack Query Docs
Rendering paginated data is a very common UI pattern and in TanStack Query, it "just works" by including the page information in the query key: