'Mutate previous data in setQueryData
In react-query, setQueryData has an overload which accepts an update function as such
setQueryData('myQuery', oldData => newData);
In this function is it ok to mutate the state of oldData and return it? For example
setQueryData('myQuery', oldData => {
oldData.foo = 42;
return oldData
}
Or is oldData immutable and must be modified with rest/spread operators or e.g. immer?
The examples all show returning a new instance, but documentation does not explicitly say one way or the other.
Mutating in place seems to work but I'm not sure if there are any pitfalls. I know with e.g. setState I would have to return a new value.
Why not return a new instance just in case? The query data is very big and I only need to modify a single field.
Update
Looking at the source code of query::setData which is what setQueryData calls, as far as I can tell the observers of the query will be notified via a call to dispatch in all cases where setQueryData is called; I don't see an early-out when oldData is reference-equal to newData. Given this, are there any risks?
Solution 1:[1]
mutating is discouraged and should not be used. The problem is that while it looks like it might work on first sight because the cached value does get changed, the reference stays the same, so react-query will not inform observers of the change.
As with most data structures in react, it is better to work immutably.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TkDodo |
