Handling client side sorting of cached data #1270
-
Hi guys, fairly new react-query user here and still trying to wrap my head around the different patterns I'm going to need in my toolset to get the job done. Currently, we are migrating a feature from redux/saga which involves a drag and drop. The order of the items after some dragging and dropping has occurred is not persisted to the server, instead, the order is used one time on the next step of the user's workflow. So I don't think a mutation/invalidation makes sense, and manually modifying the cache feels hacky unless it's in an optimistic update. Storing the records I'm sorting in UI state and sorting them there also feels wrong because then I'd have two copies of data in my server cache. What would be the "idiomatic" way to handle this situation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
It's an interesting case for sure. I would usually advice to keep server state and client state separately, and don't move server state into local state:
The problem with this approach is that this completely ignores background re-fetches that react-query might do (refetchOnWindowFocus etc). If you want to ignore them for this use-case, you can turn them off via the settings and use this approach. Modifying the cache, as you mentioned, is not good because it will also be overridden by background re-fetches. I mostly try the following approach, even though I don't know how this would combine with sorting:
This works very well if you for example use the data from react-query to pre-fill a form, but the user can change the values. If you re-fetch in the background, only the fields that the user hasn't touched will be updated. But for sorting, this seems very hard to do, because what should happen if items are added / removed on the server and you receive that update while the user is sorting...
I don't quite get that - why would you have two copies in the server cache ? You would have one copy in the query-cache and another copy for sorting in local state (like in my above example). |
Beta Was this translation helpful? Give feedback.
It's an interesting case for sure. I would usually advice to keep server state and client state separately, and don't move server state into local state:
The problem with this approach is that this completely ignores background re-fetches that react-query might do (refetchOnWindowFocus etc). If you want to ignore them for this use-case, you can turn them off via the settings and use this approach.
Modifying the cache, as you mentioned, is not good because it will als…