Structural sharing returns incorrectly mutated data on refetch when the data has a `[Symbol.iterator]` property #11514
Describe the bug#
When all of these conditions are true:
- A query's
queryFnreturns a plain object. - That object is iterable via having a
[Symbol.iterator]property. - That object has at least one other property that is a function.
- Structural sharing is enabled for that query.
- A refetch occurs for that query (e.g. via window focus, mount, interval, etc).
Then the data returned by the query following the refetch will be missing its [Symbol.iterator] property.
Your minimal, reproducible example#
https://stackblitz.com/edit/tanstack-query-i4ows4sf?file=src%2Findex.tsx
Steps to reproduce#
- Load the example app
- See that the query is fetched and the data is displayed properly
- Wait 5 seconds for an automatic refetch to happen
- See that the returned data is now missing its [Symbol.iterator] key
Expected behavior#
The returned data after refetch should have all of the same properties as before the refetch.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
Occurs on the latest version of both Chrome and Firefox.
Tanstack Query adapter#
No response
TanStack Query version#
5.102.8
TypeScript version#
No response
Additional context#
No response
TkDodo closed this
TkDodo added labelsworks as designed
@TkDodo The example object is not an iterator, it is a plain JS object that implements the iterable protocol. I'm not necessarily expecting structural sharing to work with an object like this, rather I'm expecting these two objects to both be returned unchanged:
{ name: 'myFooIter', testFunc: () => {}, // a function valued property is required for the bug to happen // This property gets removed with no warning [Symbol.iterator]: function* () { yield 'foo'; yield 'bar'; yield 'baz'; },{ name: 'myFooIter', testFunc: () => {}, // a function valued property is required for the bug to happen // This property is returned as-is myfunc: function* () { yield 'foo'; yield 'bar'; yield 'baz'; },There's more to this than just unsupported data types: removing the
testFuncproperty results in the expected behavior with all properties being preserved, so there must be some internal code that is attempting to determine whether structural sharing can be applied. If that's the case, it should bail out and return the original object.Structural sharing is enabled by default, so unsupported data should at least show a warning in development mode, rather than a subtle bug being created.
they might have the iterator implemented differently though. An object with an iterator is not a
plainObjectso we are not sharing it in our implementation.
Sign in to join this conversation.
Iterators are not json stringifyable so we don’t check them during structural sharing. If you want that, you need to provide your own
structuralSharingfunction.