Skip to content
Source
Sign inSign up
TanStack/query

Make undefined an illegal cache value (for successful queries) #2925

ClosedTkDodo opened this issue 5 comments
TkDodocommented

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 undefined is returned, we do not create or update the cache entry
    • that means if we have a previous value and undefined is returned - undefined is not written to the cache, and observers are not informed about that.
    • this is technically breaking if undefined is 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
  1. TkDodo added labelsv4

  2. I face the same issue, I guess that the following code should be valid code:

          queryClient.setQueryData("Key", old => old);
  3. While we're at it: what should the type of setQueriesData be? If it only traverses existing queries, I guess it should use Updater<TData, TData> and not Updater<TData | undefined, TData> or Updater<TData | undefined, TData | undefined> (the latter is what the linked PR gives).

  4. @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.

  5. TkDodo closed this

  6. :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:

  7. tannerlinsley added labelsreleased on @alpha

  8. :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:

  9. tannerlinsley added labelsreleased on @beta

Sign in to join this conversation.