Skip to content

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

Closed

Description

@TkDodo

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

Activity

  1. added this to the v4 milestone on Nov 11, 2021
  2. kayvaninvemo commented on Jan 8, 2022

    @kayvaninvemo

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

          queryClient.setQueryData("Key", old => old);
    
  3. neongreen commented on Jan 30, 2022

    @neongreen

    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. TkDodo commented on Jan 30, 2022

    @TkDodo
    CollaboratorAuthor

    @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. tannerlinsley commented on Feb 9, 2022

    @tannerlinsley
    Member

    🎉 This issue has been resolved in version 4.0.0-alpha.11 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

  6. tannerlinsley commented on Apr 2, 2022

    @tannerlinsley
    Member

    🎉 This issue has been resolved in version 4.0.0-beta.1 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions