Make undefined an illegal cache value (for successful queries) #2925
Please see this discussion
This is an ever-recurring issue that you can't bail out of updates with setQueryData. But because the updater function gives you a potentially undefined value (if there is no cache entry for the key yet), TypeScript is very unhappy because you're supposed to create a new cache entry, and there is no "bailing out of it" because react-query actually creates the cache entry before the functional updater of setQueryData is called.
Proposed solution#
As stated here:
- let's allow the setQueryData functional updater to return undefined
- signature: T | ((prev: T | undefined) => T | undefined)
- if
undefinedis returned, we do not create or update the cache entry - that means if we have a previous value and
undefinedis returned -undefinedis not written to the cache, and observers are not informed about that. - this is technically breaking if
undefinedis a legit cache entry value for someone
This would be in-ine with what the initialData function already does: if undefined is returned from that, it is not persisted to the cache.
Also, if a fetch function returns undefined, we should:
- transform it to a failed promise (error)
- warn during development mode about it
TkDodo added labelsv4
While we're at it: what should the type of
setQueriesDatabe? If it only traverses existing queries, I guess it should useUpdater<TData, TData>and notUpdater<TData | undefined, TData>orUpdater<TData | undefined, TData | undefined>(the latter is what the linked PR gives).@neongreen A query could exist but still have undefined data in the cache, e.g. if it's in idle or error state. So the latter is correct.
TkDodo closed this
:tada: This issue has been resolved in version 4.0.0-alpha.11 :tada:
The release is available on:
Your semantic-release bot :package::rocket:
tannerlinsley added labelsreleased on @alpha
:tada: This issue has been resolved in version 4.0.0-beta.1 :tada:
The release is available on:
Your semantic-release bot :package::rocket:
tannerlinsley added labelsreleased on @beta
Sign in to join this conversation.
I face the same issue, I guess that the following code should be valid code: