modifying data fetched by React-Query on the client side
Hi all,
I'm new to react-query and I'm building a project and trying to learn along the way. I'm stuck in a requirement and would appreciate the help.
Here's an use case:
I'm fetching the user's list from its API through react-query (say, usersList) and displaying it in a list format.
I have a SortMenu component which has options like sort by name, sort by created date etc.
I need a way to sort the usersList.
What is the best way to do this?
Note: I'm using zustand for client state management.
Thanks in advance 🙂
12 Replies
xenial-black•2y ago
is the sorting happening on the backend or the frontend ?
extended-salmonOP•2y ago
Happening at the frontend..
xenial-black•2y ago
well then react-query has nothing to do with it. pseudo-code:
extended-salmonOP•2y ago
Wont this sortbyname function be called every time the query fetches data from either the cache or the server?
I'm also wondering if this would re-render the component even if the usersList doesn't change?
sensitive-blue•2y ago
I was sorta wondering something similar. If I needed to transform my results with a
map
is that better to do in the queryFn
or outside like you have with sortByName
? If it's outside wouldn't a render cause a potentially expensive sort/map to happen again?xenial-black•2y ago
If it's expensive, wrap it in useMemo.
sensitive-blue•2y ago
Well yeah, that's a given but I guess my question is "sneaking" stuff into the queryFn anti-React/react-query?
extended-salmonOP•2y ago
Doesn't react-query by default memoize the fetched data?
Also I tried both your approach and @troywoy approach by calling the sortByName function in the "select" property of useQuery.. and both seem to be working fine in terms of usability..
I'm just curious about which approach would be better in terms of performance or any other aspect if there is..
sensitive-blue•2y ago
Yeah react-query does a lot for you. Dominik made a post recently kinda touching on that: https://tkdodo.eu/blog/why-you-want-react-query. But yeah, I'm curious about best approaches too
xenial-black•2y ago
React Query Data Transformations
Learn the possibilities to perform the quite common and important task of transforming your data with react-query
xenial-black•2y ago
Note that you can't transform in the queryFn if there is a dependency. The queryFn wouldn't run if the sorting changes unless changing the sorting should trigger a new fetch (but why would it if the sorting happens on the client only)
extended-salmonOP•2y ago
According to the blog,
I guess for my use-case, "select" with useCallback works the best...