Skip to content
Source
Sign inSign up
TanStack/query

DefaultError type fallback type has too strong guarantees #7872

Send to my agent
Closedbvanderdrift(GitHub profile, opens in a new tab) opened this issue 3 comments

Describe the bug

The type of error is by default Error. When using persistQueryClient it will serialize to JSON. Error is not serializable. JSON.stringify(new Error('some message')) will return "{}".

This leads persisted errors to be of type {}, but useQuery defaults to Error. Therefore the type fallback is incorrect.

Your minimal, reproducible example

https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgVwM4FMCKz1QJ5wC+cAZlBCHAORToCGAxjALQCOO+VAUFwxAHap4adADEIEOAF44ACgCU0gHyIucdXD6D47XARkjse2QjUbzu-AGl0eAFxwA2lRISqAXQA0Z8+st5RfgcFZVVfcLgYAAtyAHc4fnR4gFEocihZKhh0ISp5AG4fX0Iiwnkec2ASWX8AOlx02pAc1DoAc3R5UwjNAVQIABt0WoGINpqOPHq06CaW9s7C8xKi2hhkKH44f0KVriA

Steps to reproduce

  1. use useQuery
  2. look at the type of error

Expected behavior

The type of error defaults to Error, expected unknown.

How often does this bug happen?

Sometimes

Screenshots or Videos

No response

Platform

  • OS: Android, iOS
  • Framework: React Native

Tanstack Query adapter

react-query

TanStack Query version

5.51.16

TypeScript version

5.0.4

Additional context

I actually notice the types are as expect in my reproducable code, but looking at the code of the latest version of this package the fallback is still Error.

  1. sorry, we're not gonna revert back to unknown. The Error type assumption is "optimistic", yes, because it holds true for 99% of cases. It also falls apart if you trow 25 in your queryFn, because 25 is also not an Error.

    We've documented how you can opt out of that typings here:

    https://tanstack.com/query/v5/docs/framework/react/typescript#registering-a-global-error

    Basically, you want:

    import '@tanstack/react-query'
    
    declare module '@tanstack/react-query' {
      interface Register {
        defaultError: unknown
      }
    }

    Regarding persistence: We don't persist queries that are in "error" state for that exact reasons: errors aren't persistable. So to get to an Error being persisted with the plugin, you have to opt-in by implementing the shouldDehydrateQuery option. This is also documented here: https://tanstack.com/query/v5/docs/framework/react/reference/hydration#limitations

  2. TkDodo closed this

  3. TkDodo added labelswontfix

  4. @TkDodo, allright, clear alternate solution. Thanks for the rapid response, no need to be sorry.

Sign in to join this conversation.