#Programmatically set error on query with query client

7 messages · Page 1 of 1 (latest)

jagged elbow
#

Hey gang. I know it's possible to set query data using queryClient.setQueryData. Is it possible to set the error for a query? I can't seem to find the appropriate API to do that.

As context: I've created a live query framework on top of React Query that fetches initial data while subscribing to updates via websockets. When websocket updates come in, the query cache is updated with queryClient.setQueryData. However, it's possible for websocket updates to return errors after the initial data is returned. I would love to be able to rely on React Query for handling these errors, but I don't know of a way to tell React Query that there is an error aside from throwing an error in the query function, which would be complicated to do in this circumstance.

upbeat oxide
#

interesting case - we indeed do not have an api for that, apart from:

queryClient.prefetchQuery({
  queryKey: myKey,
  queryFn: () => throw new Error("my error")
})

a bit hack-ish and also async (no sync error setting) but maybe it helps your case?

jagged elbow
#

I frickin' love it. Thanks @upbeat oxide - that hack is just what I need!

#

I'm just blown away by how simultaneously elegant and devilish that solution is 😈

upbeat oxide
#

hmm, this might have side-effects I haven't anticipated 😅 . For example, this queryFn is then stored and used for refetches 🤔

jagged elbow
#

I'm not worried about that in my case. I've turned off refetches, and rely entirely on the websocket for updates.

upbeat oxide
#

just fyi, I found another solution:

const query = queryClient.getQueryCache.build(queryClient, options)

query.setQueryState({
 ...query.getQueryState,
 error: new Error("my error")
})

that's pretty low level though, so you'd also need to set errorUpdateCount and errorUpdatedAt. If the prefetch works for you, stick with that 👍