Be careful not to mutate the cache data when optimistic updating #1325
Replies: 3 comments 1 reply
-
I think it is quite common in react that you avoid to mutate whenever possible. You don’t mutate state in classes - you call setState. You don’t mutate state in redux - you return a new object. You don’t mutate props that come into a component etc. This is a general principle that doesn’t apply to react query alone, but if you feel that the docs could be improved (e.g. stating somewhere that the queryCache should be treated immutable) i guess that wouldn’t hurt :) |
Beta Was this translation helpful? Give feedback.
-
I think this discussion is related: #1304 |
Beta Was this translation helpful? Give feedback.
-
hi, me english is bad. I have the same problem. i don't understand what is the problem about it: can you describe me why happend that? Thanks and regards. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I though I'd share my day's frustration in case it helps someone else ... and perhaps someone can think of a good way of updating the documentation for clarity.
Here's my story: I was basically doing the equivalent of this:
(the underlying cached data is an array of objects)
The problem is that this mutates the underlying cache data. The fix is to deep clone the
data
array before making a change of the object. The terrible part is that it works ... until the api call throws an error. Then you notice that your rollback data isn't what you're expecting. You throw in a couple of console.logs trying to figure out what's going on and it appears that your original cache data is changed before your setQueryData call is even run, making you think you're in the twilight zone ... or possibly just on drugs.The current documentation doesn't mention this directly, and the examples kinda skirt around the issue. But surely this is a pretty common use case(?)
Beta Was this translation helpful? Give feedback.
All reactions