queryFn won't refetch with new state (it sort of does but not the way i expected)
Okay so here i am trying to basically fetch some data from an api using tanstack query with material UI table pagination which lets me select how many rows of data i want per page. The API i made is able to plug that value to fetch any amount of data using the limit param.
Anyway the setter
setRowsPerPage
in the handleChangeRowsPerPage
function works correctly when i select 25 or any other value from the dropdown in the table pagination UI and i can see the console log of the updated state
The console log in the query function logs this when i first select 25 from pagination UI.
The problem is when the query function is called again with refetch()
, somehow the rowsPerPage
value used is still the old default not updated value of 10. I want it to use the updated value of what i selected in the UI.
Then comes the part where i meant it sort of works.
So after i select 25 from the pagination and then when i select 10 again, the refetch()
gets triggered and then this time it fetches with rowsPerPage
as value of 25. Always it is behind a number. Not the number i set.
Basically in summary, the refetch()
function gets called but it always uses the previous state and not the state i set.
here is the code what i am working with https://pastecode.io/s/xzscd81d
How can i fix this?5 Replies
sensitive-blue•2y ago
you don't need refetch. Put everything you use in the queryFn into the queryKey and watch the magic happen
sensitive-blue•2y ago
+ use our lint rules: https://tanstack.com/query/v5/docs/react/eslint/exhaustive-deps
Exhaustive dependencies for query keys | TanStack Query Docs
Query keys should be seen like a dependency array to your query function: Every variable that is used inside the queryFn should be added to the query key.
This makes sure that queries are cached independently and that queries are refetched automatically when the variables changes.
sensitive-blue•2y ago
Query Keys | TanStack Query Docs
At its core, TanStack Query manages query caching for you based on query keys. Query keys have to be an Array at the top level, and can be as simple as an Array with a single string, or as complex as an array of many strings and nested objects. As long as the query key is serializable, and unique to the query's data, you can use it!
Simple Que...
sensitive-blue•2y ago
Practical React Query
Let me share with you the experiences I have made lately with React Query. Fetching data in React has never been this delightful...
sensitive-blue•2y ago
oh and here as well: https://tkdodo.eu/blog/react-query-fa-qs#how-can-i-pass-parameters-to-refetch
React Query FAQs
Answering the most frequently asked React Query questions